AJAX总结--JS原生Ajax & jQuery Ajax

原生Ajax

get请求流程

  • 创建ajax请求对象:

    大多数浏览器为XMLHTTPRequest(),高版本IE浏览器为ActiveXObject("Msxml2.XMLHTTP"),低版本IE浏览器为ActiveXObject("Microsoft.XMLHTTP")

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    function  ajaxFunction(){
    var xmlHttp;
    try{ // Firefox, Chrome, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
    catch (e){
    try{// Internet Explorer(高版本)
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e){
    try{// Internet Explorer(低版本)
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e){}
    }
    }
    return xmlHttp;
    }
  • 使用open方法创建http请求,并设置请求地址

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    //执行get请求
    function get() {

    //1. 创建xmlhttprequest 对象
    var xhr = ajaxFunction();

    //2. 发送请求。
    /*
    * 参数一: 请求类型 GET or POST
    * 参数二: 请求的路径
    * 参数三: 是否异步, true or false
    */
    xhr.open("GET" ,"TestServlet" ,true );
    xhr.send();
    }
  • 如果发送请求的同时,还想获取数据,那么代码如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    //执行get请求
    function get() {

    //1. 创建xmlhttprequest 对象
    var xhr = ajaxFunction();

    //2. 设置请求参数
    xhr.open("GET" ,"TestServlet?name=aa&age=18" ,true );

    //3. 获取响应数据 注册监听的意思。 一会准备的状态发生了改变,那么就执行 = 号右边的方法
    xhr.onreadystatechange = function(){
    // readyState的值一共有5个状态,参见下表
    // readyState == 4 表示请求已经完成, 再判断状态码是否是200,200表示服务端正常响应(没有报错)
    if(xhr.readyState == 4 && xhr.status == 200){
    //弹出响应的信息
    alert(request.responseText);
    }
    }

    // 4. 发送请求
    xhr.send();
    }

post请求流程

Post请求方式和Get请求基本相同,只是由于post方式传递数据是模仿form表单传递给服务器的,要设置header头协议

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//1. 创建对象
// 和get请求一样

function post() {
//1. 创建请求对象
var xhr = ajaxFunction();

// 2. 设置请求地址、参数、类型(post、get)
xhr.open("post", "StudentServlet", true);

//3. 获取响应数据 注册监听的意思。 一会准备的状态发生了改变,那么就执行 = 号右边的方法
xhr.onreadystatechange = function(){
//前半段表示 已经能够正常处理。 再判断状态码是否是200
if(xhr.readyState == 4 && xhr.status == 200){
//弹出响应的信息
console.log("请求完成");
var h1 = document.getElementById("h1");
h1.innerHTML = xhr.responseText;
}
}

// 4. 如果使用的是post方式带数据,那么 这里要添加头, 说明提交的数据类型是一个经过url编码的form表单数据
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

// 5. 发送请求
// 如果是GET请求,参数写在这里是无效的
xhr.send("id=555");
}

jQuery Ajax

$.ajax()的使用

该方法用于执行Ajax请求,常用于其他jQuery Ajax方法不能完成的请求,是jQuery中Ajax系列方法的的底层实现,其他方法都是在它的基础上给我们封装的更方便使用的方法。

形式:$.ajax(url, [settings]);
常用字段:

  • url:链接地址,字符串

  • type“POST"“GET",请求类型

  • data:需发送到服务器的数据,GET与POST都可以,格式为{A: ‘…’, B: ‘…’}

  • dataType:服务器响应的数据类型,字符串表示;当填写为json时,回调函数中无需再对数据反序列化为json

  • success:请求成功后,服务器回调的函数

  • error:请求失败后,服务器回调的函数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    $.ajax("TestServlet", {
    type: "GET",
    data: {
    action: "json",
    uname: "zhangsan"
    },
    dataType: "json",
    success: function(data, status_text){
    console.log(data);
    console.log("status_text: " + status_text);
    },
    error: function(xhr, textStatus, errorThrow) {
    console.log("请求失败");
    }
    });

$.get()的使用

$.get()方法使用GET方式来进行异步请求,它的语法结构为:

$.get(url, data, func, dataType);

1
2
3
4
5
6
7
8
9
10
11
12
/*
* 参数:
* url: 请求地址
* data: 待发送 Key/value 参数
* fn: 请求成功后回调函数
* type: 返回内容格式,xml, html, script, json, text, _default
*/

$.get( "url",{pid:pid} ,function(data,status_text){
console.log(data);
console.log("status_text: " + status_text);
},"json" ); // 指定请求返回的格式是json,jquery会帮我们把服务端返回的json字符串转换成js的json对象

$.post()的使用

$.post()方法使用POST方式来进行异步请求,它的语法结构为:

$.post(url, data, function, dataType);

1
2
3
4
5
6
7
8
9
10
11
12
/*
* 参数:
* url: 请求地址
* data: 待发送 Key/value 参数
* fn: 请求成功后回调函数
* type: 返回内容格式,xml, html, script, json, text, _default
*/

$.post( "url",{pid:pid} ,function(data,status){
console.log(data);
console.log("status_text: " + status_text);
},"json" ); // 指定请求返回的格式是json,jquery会帮我们把服务端返回的json字符串转换成js的json对象

$.getJSON();的使用

$.getJSON()是专门为ajax获取json数据而设置的,该方法使用GET方式执行Ajax请求,从服务器加载JSON格式数据,并且支持跨域调用,它的语法结构为:

$.getJSON(url, data, func);

因为确定服务器返回的是json编码的数据,所以相较于$.get()不用再指定dataType。

1
2
3
$.getJSON("url", {id:1, name: "zhangsan"} function(json){
console.log(json);
});

以上四个方法的关系和区别?

$.ajax()是jQuery的底层AJAX实现,$.get()$.post()是简单易用的jQuery高层AJAX实现

$.getJSON()是通过 HTTP GET 请求载入 JSON 数据。