ajax标准格式

jquery向服务器发送一个ajax请求后,可以返回多种类型的数据格式,包括:html,xml,json,text等。

$.ajax({
    url:"http://www.test.com",    //请求的url地址
    dataType:"json",   //返回格式为json
    async:true,//请求是否异步,默认为异步,这也是ajax重要特性
    data:{"id":"1","name":"名字"},    //参数值
    type:"GET",   //请求方式
    beforeSend:function(){
        //请求前的处理
    },
    success:function(req){
        //请求成功时处理
    },
    complete:function(){
        //请求完成的处理
    },
    error:function(){
        //请求出错处理
    }
});

举例:

//发送ajax请求
$.ajax({

url:path+"/user/login.do",

type:"post",
data:{"name":name,"password":password},

dataType:"json",

success:function(result){
//result是服务器返回的JSON结

if(result.status==0){

//将用户信息保存到Cookie
var
userId=result.data.cn_user_id;
addCookie
("userId",userId,2);

window.location.href="edit.html";
}else if
(result.status==1){ //用户名错

$("#count_span").html(result.msg);
}else if
(result.status==2){
$("#password_span").html
(result.msg);
}
},

error:function(){

alert("登录失败!");
}
});

原文地址:https://www.cnblogs.com/mike-mei/p/9534132.html