Asp+Ajax实现无刷新增加好友

由于工作关系,要做个人空间,其中有一功能是增加对方为好友.如图:

用到的方法是ajax,费话少说贴切代码:

<a href="javascript:void(0);" onClick="add_username('<%= rs("username") %>');">加为好友</a>,用到的js验证:

<script language = "JavaScript" src="ajax.js"></script>
<script>
//add user
function add_username(usr){
//
var sta;
var username=usr;
if(username!=""){
if(username!=""){
username="username="+username;
sta=posthttp(username,"Add_Friend.asp");
if(sta==false){
alert("添加失败,服务器错误");
}else{
if(parseInt(sta)==1)
alert("恭喜您,好友添加成功!");
else
alert(sta);
}
}else{
alert("请输入好友名");
}
}
}
</script>

ajax.js代码:

http_request = false;

if (window.XMLHttpRequest) {
//对于Mozilla、Netscape、Safari等浏览器,创建XMLHttpRequest
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
//如果服务器响应的header不是text/xml,可以调用其它方法修改该header
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) {
// 对于Internet Explorer浏览器,创建XMLHttpRequest
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
return http_request;
}


//获得Url 的responseText
function getResponseText(url)
{
http_request=getRequest();
http_request.open('GET', url, false);
http_request.send(null);

if (http_request.readyState == 4)
   {
   // 收到完整的服务器响应
   if (http_request.status == 200) {
   //HTTP服务器响应的值OK
     requestdoc = http_request.responseText;
     //将服务器返回的字符串写到页面中ID为message的区域
}
    else {
     requestdoc = http_request.status;
    }
   }
return requestdoc;
}

//POST 提交数据
function posthttp(str,url){
http_request=getRequest();
http_request.open('POST',url,false);
http_request.setRequestHeader("Content-Length",str.length);
http_request.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");

http_request.send(str);
if (http_request.readyState == 4)
{
   // 收到完整的服务器响应
   if (http_request.status == 200) {
//HTTP服务器响应的值OK
    requestdoc = http_request.responseText;
    //将服务器返回的字符串写到页面中ID为message的区域
return requestdoc;
}else{
     //requestdoc = http_request.status;
return false;
   }
}
}

//获得Url 的responseXML
function getXMLResponseText(url)
{
http_request=getRequest();
http_request.open('GET', url, false);
http_request.send(null);

if (http_request.readyState == 4)
   {
   // 收到完整的服务器响应
   if (http_request.status == 200) {
     //HTTP服务器响应的值OK
     requestdoc = http_request.responseXML;
     //将服务器返回的字符串写到页面中ID为message的区域
}
    else {
     requestdoc = http_request.status;
    }
   }
return requestdoc;
}

然后在Add_Friend.asp里处理一下就可以了.

<%
Response.ContentType="text/html; charset=gb2312"
'处理程序就不贴了,先判断一下用户是否登陆,好友的用户名是否传过来了,好友的用户名是否合法,该好友是否第一次增加等信息,如果增加正确,就返回1

If Add_Friend = 1 Then '如果能正确增加好友,Add_Friend=1
response.write "1" '这个值自动的返回给js
Else
response.write "出错了"'请检查代码
End If
%>

返回提示如图:

你可能感兴趣的:(Ajax)