詳細介紹用jQuery發送ajax的幾種情況,以及$.ajax(),$.get(),$.post()三者的關系. ajax是一個方法,方法的參數{}是一個對象,里面是對象的屬性和值
### $.ajax()
```javascript
//ajax是一個方法,方法的參數{}是一個對象,里面是對象的屬性和值
$.ajax({
type : "post", //發送類型,get或post,默認為get
async : true, //true為異步,false為同步,默認為true
url : "http://localhost:8080/comment.php", //請求的后臺地址
data : "name=wang&comment=hello", //往后臺傳遞的參數,可以是object或string類型,但最終都會被轉換為字符串格式
data : {name:"wang",comment:"hello"},
data : {foo:["bar1","bar2"]},//被轉換為 &foo=bar1&foo=bar2
data : $("#form1").serialize(),
dataType : "text", //預期服務器返回的數據類型,可以為text,json,html,xml,script等,text表示返回數據為純文本字符串
cache : true, //true使用瀏覽器緩存,false不適用,默認為true
contentType : //string類型,默認為"application/x-www-form-urlencoded",適合大多數應用場合
success : statechange //成功時的回調函數
});
function?statechange(data)?{
//用于接收應答數據的回調函數,參數在data中
}
```
<br/>
### $.get()
~~~
$.get(url,data,success(response,status,xhr),dataType)
~~~
url //必需。規定將請求發送的哪個 URL。
data //可選。規定連同請求發送到服務器的數據。
success(response,status,xhr) //可選。規定當請求成功時運行的函數。
額外的參數: response // 包含來自請求的結果數據 status // 包含請求的狀態 //xhr - 包含 XMLHttpRequest 對象 dataType //可選。規定預計的服務器響應的數據類型。
默認地,jQuery 將智能判斷。
等價于:
~~~
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
~~~
<br/>
### $.post
~~~
$.post(url,data,success(data, textStatus, jqXHR),dataType)
~~~
等價于:
~~~
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
~~~
eg:
~~~
$.post("Ajax.aspx", { Action: "post", Name: "lulu" },
function?(data,?textStatus){
// data 可以是 xmlDoc, jsonObj, html, text, 等等.
//this;
// 這個Ajax請求的選項配置信息,請參考jQuery.get()說到的this
alert(data.result);
}, "json");
~~~