您的位置:首页 > Web前端 > JQuery

JQuery中$.ajax()方法参数详解

2014-08-16 00:40 281 查看
url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址。

type: 要求为String类型的参数,请求方式(post或get)默认为get。注意其他http请求方法,例如put和

delete也可以使用,但仅部分浏览器支持。

timeout: 要求为Number类型的参数,设置请求超时时间(毫秒)。此设置将覆盖$.ajaxSetup()方法的全局设

置。

async:要求为Boolean类型的参数,默认设置为true,所有请求均为异步请求。

如果需要发送同步请求,请将此选项设置为false。注意,同步请求将锁住浏览器,用户其他操作必须等

待请求完成才可以执行。

cache:要求为Boolean类型的参数,默认为true(当dataType为script时,默认为false)。

设置为false将不会从浏览器缓存中加载请求信息。

data: 要求为Object或String类型的参数,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格

式。get请求中将附加在url后。防止这种自动转换,可以查看processData选项。对象必须为key/value格

式,例如{foo1:"bar1",foo2:"bar2"}转换为&foo1=bar1&foo2=bar2。如果是数组,JQuery将自动为不同

值对应同一个名称。例如{foo:["bar1","bar2"]}转换为&foo=bar1&foo=bar2。

dataType: 要求为String类型的参数,预期服务器返回的数据类型。如果不指定,JQuery将自动根据http包mime

信息返回responseXML或responseText,并作为回调函数参数传递。

可用的类型如下:

xml:返回XML文档,可用JQuery处理。

html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。

script:返回纯文本JavaScript代码。不会自动缓存结果。除非设置了cache参数。注意在远程请求

时(不在同一个域下),所有post请求都将转为get请求。

json:返回JSON数据。

jsonp:JSONP格式。使用SONP形式调用函数时,例如myurl?callback=?,JQuery将自动替换后一个

“?”为正确的函数名,以执行回调函数。

text:返回纯文本字符串。

beforeSend:要求为Function类型的参数,发送请求前可以修改XMLHttpRequest对象的函数,例如添加自定义

HTTP头。在beforeSend中如果返回false可以取消本次ajax请求。XMLHttpRequest对象是惟一的参

数。

function(XMLHttpRequest){

this; //调用本次ajax请求时传递的options参数

}

complete:要求为Function类型的参数,请求完成后调用的回调函数(请求成功或失败时均调用)。

参数:XMLHttpRequest对象和一个描述成功请求类型的字符串。

function(XMLHttpRequest, textStatus){

this; //调用本次ajax请求时传递的options参数

}

success:要求为Function类型的参数,请求成功后调用的回调函数,有两个参数。

(1)由服务器返回,并根据dataType参数进行处理后的数据。

(2)描述状态的字符串。

function(data, textStatus){

//data可能是xmlDoc、jsonObj、html、text等等

this; //调用本次ajax请求时传递的options参数

error:要求为Function类型的参数,请求失败时被调用的函数。该函数有3个参数,即XMLHttpRequest对象、错

误信息、捕获的错误对象(可选)。

ajax事件函数如下:

function(XMLHttpRequest, textStatus, errorThrown){

//通常情况下textStatus和errorThrown只有其中一个包含信息

this; //调用本次ajax请求时传递的options参数

}

contentType:要求为String类型的参数,当发送信息至服务器时,内容编码类型默认

为"application/x-www-form-urlencoded"。该默认值适合大多数应用场合。

dataFilter:要求为Function类型的参数,给Ajax返回的原始数据进行预处理的函数。

提供data和type两个参数。data是Ajax返回的原始数据,type是调用jQuery.ajax时提供的

dataType参数。函数返回的值将由jQuery进一步处理。

function(data, type){

//返回处理后的数据

return data;

}

global:要求为Boolean类型的参数,默认为true。表示是否触发全局ajax事件。设置为false将不会触发全局

ajax事件,ajaxStart或ajaxStop可用于控制各种ajax事件。

ifModified:要求为Boolean类型的参数,默认为false。仅在服务器数据改变时获取新数据。

服务器数据改变判断的依据是Last-Modified头信息。默认值是false,即忽略头信息。

jsonp:要求为String类型的参数,在一个jsonp请求中重写回调函数的名字。

该值用来替代在"callback=?"这种GET或POST请求中URL参数里的"callback"部分,例如

{jsonp:'onJsonPLoad'}会导致将"onJsonPLoad=?"传给服务器。

username:要求为String类型的参数,用于响应HTTP访问认证请求的用户名。

password:要求为String类型的参数,用于响应HTTP访问认证请求的密码。

processData:要求为Boolean类型的参数,默认为true。默认情况下,发送的数据将被转换为对象(从技术角度

来讲并非字符串)以配合默认内容类型"application/x-www-form-urlencoded"。如果要发送DOM

树信息或者其他不希望转换的信息,请设置为false。

scriptCharset:要求为String类型的参数,只有当请求时dataType为"jsonp"或者"script",并且type是GET时

才会用于强制修改字符集(charset)。通常在本地和远程的内容编码不同时使用。

案例代码:

$(function(){

$('#send').click(function(){

$.ajax({

type: "GET",

url: "test.json",

data: {username:$("#username").val(), content:$("#content").val()},

dataType: "json",

success: function(data){

$('#resText').empty(); //清空resText里面的所有内容

var html = '';

$.each(data, function(commentIndex, comment){

html += '<div class="comment"><h6>' + comment['username']

+ ':</h6><p class="para"'
+ comment['content']

+ '</p></div>';

});

$('#resText').html(html);

}

});

});

});

顺便说一下$.each()函数:

$.each()函数不同于JQuery对象的each()方法,它是一个全局函数,不操作JQuery对象,而是以一个数组或者对象作为第1个参数,以一个回调函数作为第2个参数。回调函数拥有两个参数:第1个为对象的成员或数组的索引,第2个为对应变量或内容。


jQuery带参数的ajax调用WebService

2009-08-05 来自:Mainz's Space 字体大小:【大 中 小】

摘要:在调试jQuery带参数的ajax调用WebService的时候,被参数的问题搞了一下,问题是这样的:首先在服务器端(C#, .NET2.0)定义了一个WebService, 里面有两个方法,其中一个返回:List<Person>
GetPersonList(string input), 返回的是自定义的集合。

在调试jQuery带参数的ajax调用WebService的时候,被参数的问题搞了一下,问题是这样的:

首先在服务器端(C#, .NET2.0)定义了一个WebService, 里面有两个方法,其中一个返回:List<Person> GetPersonList(string input), 返回的是自定义的集合。

WebService代码如下:

1: using System;

2: using System.Collections.Generic;

3: using System.Collections.ObjectModel;

4: using System.Web;

5: using System.Collections;

6: using System.Web.Services;

7: using System.Web.Services.Protocols;

8:

9: [WebService(Namespace = "http://semenoff.dk/")]

10: [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

11: [System.Web.Script.Services.ScriptService()]

12: public class MySampleService : System.Web.Services.WebService

13: {

14:     public MySampleService()

15:     {

16:         //Uncomment the following line if using designed components

17:         //InitializeComponent();

18:     }

19:

20:     [WebMethod]

21:     public string GetServerResponse(string callerName)

22:     {

23:         if(callerName== string.Empty)

24:             throw new Exception("Web Service Exception: invalid argument");

25:

26:         return string.Format("Service responded to {0} at {1}", callerName, DateTime.Now.ToString());

27:     }

28:

29:

30:     [WebMethod]

31:     public List<Person> GetPersonList(string input)

32:     {

33:         List<Person> ret = new List<Person>();

34:

35:         Person p = new Person();

36:         p.ID = "001";

37:         p.Value = "Jason Hu";

38:

39:         ret.Add(p);

40:

41:         p = new Person();

42:         p.ID = "002";

43:         p.Value = "Thomas Li";

44:

45:         ret.Add(p);

46:

47:         //System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();

48:         //return json.Serialize(ret);

49:

50:         return ret;

51:     }

52:

53: }

54:

55: public class Person

56: {

57:     public string ID { get; set; }

58:     public string Value { get; set; }

59: }

60:


客户端jQuery用ajax调用这个WebService,其中jQuery的ajax的data参数是常量可以:

1: $.ajax({

2:         type: "POST",

3:         contentType: "application/json",

4:         url: "./WebServices/MySampleService.asmx/GetServerResponse",

5:         data:"{input:56}", // ************* 常量 ******************

6:         dataType: 'json',

7:         success: function(result) {

8:         alert("jQuery callback: " + result);

9:         },

10:         error: function(){

11:           alert("Error occured.");

12:         }

13:      });


但jQuery的ajax的data参数是变量写成这样就不行:

1: $.ajax({

2:         type: "POST",

3:         contentType: "application/json",

4:         url: "./WebServices/MySampleService.asmx/GetServerResponse",

5:         data:"{input:" + user + "}", //******* 此处错,回调Error****************

6:         dataType: 'json',

7:         success: function(result) {

8:         alert("jQuery callback: " + result);

9:         },

10:         error: function(){

11:           alert("Error occured.");

12:         }

13:      });


最后继续折腾加个单引号,写成这样data:'{"callerName":"'+user+'"}' 就没问题了:

1: /// <reference src="jquery-1.3.2.js"/>

2:

3: var MyNameSpace = MyNameSpace || {};

4: MyNameSpace.Auth={};

5:

6: MyNameSpace.Auth.TestJQuery = function(user)

7: {

8:   $.ajax({

9:         type: "POST",

10:         contentType: "application/json",

11:         url: "./WebServices/MySampleService.asmx/GetServerResponse",

12:         data:'{"callerName":"'+user+'"}', //注意格式!!"{callerName:abc}",可以,但 "{callerName:"+user+"}"不行,Error!

13:         dataType: 'json',

14:         success: function(result) {

15:           alert("jQuery callback: " + result);

16:         },

17:         error: function(){

18:           alert("Error occured.");

19:       } 

20:      });

21:

22:       $.ajax({

23:                 type: "POST",

24:                 contentType: "application/json",

25:               url: "./WebServices/MySampleService.asmx/GetPersonList",

26:                 data: '{"input":"'+user+'"}', ////注意格式!"{input:56}",可以,但 "{input:"+user+"}"不行,Error!

27:                 dataType: 'json',

28: //                beforeSend: function(){

29: //                    $("#tipsDiv").show();

30: //                    $("#tipsDivGT").text("Searching.... please wait");

31: //                  },

32: //                error: function(){

33: //                    $("#tipsDivGT").text("Error occured!!");

34: //                  },

35:                 success: function(result) {

36:

37:                         //$('#dictionary').append(this.toString() + " ");

38:                      // alert(result.join(" | "));

39:

40:                    $(result).each(function() {

41:                        alert(this['ID'] + " " + this['Value']);

42:                     });

43:

44:               }

45:             });

46: }

47:

48: $(function() {

49:   $("#btnTest").click(function() {

50:         MyNameSpace.Auth.TestJQuery( $("#tbUserName").attr("value") );

51:     });

52:

53:   }

54:

55: );


立此存照希望对被同样小问题困扰的同学有用!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: