jquery中通过ajax调用webservice传递数组参数的问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jquery中通过ajax调用webservice传递数组参数的问题相关的知识,希望对你有一定的参考价值。
如题.
还是直接用例子说明来的直接些.
本人的项目中通过jquery.ajax调用webservice.
客户端代码如下:
1 $.ajax({ 2 url: "test/xxx.asmx", 3 type: ‘POST‘, 4 dataType: ‘xml‘, 5 timeout: 1000, 6 data: { name: "zhangsan", tags: ["aa", "bb", "cc"] }, 7 error: function(xml) { 8 alert(xml.responseText); 9 }, 10 success: function(xml) { 11 alert("OK"); 12 } 13 14 });
服务端代码如下:
1 [WebMethod] 2 public XmlDocument xxx(string name, string [] tags ) 3 { 4 return sth; 5 }
总是抛出异常.
问题出现在这里:
下面是HTTP数据:
POST http://xxx.com/xxx.asmx/xxx HTTP/1.1 Host: center.cmis.htpc.com.cn Connection: keep-alive Content-Length: 55 Cache-Control: max-age=0 Origin: http://xxx.com User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (Khtml, like Gecko) Chrome/14.0.835.186 Safari/535.1 Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Accept: application/xml, text/xml, */*; q=0.01 Referer: http://xxx.com/xxx.aspx Accept-Encoding: gzip,deflate,sdch Accept-Language: zh-CN,zh;q=0.8 Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3 name=zhangsan&tags%5B%5D=aa&tags%5B%5D=bb&tags%5B%5D=cc
而它期望的格式是如下的:
POST /xxx.asmx/xxx HTTP/1.1
Host: xxx.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length
name=string&tags=string&tags=string
比较上面粗体,post的数据除了问题. 正确的应该如下:
name=zhangsan&tags=aa&tags=bb&tags=cc
看来问题出在jquery.ajax上面了.见代码(jquery.1.8.3.js)
1 function buildParams(prefix, obj, traditional, add) { 2 var name; 3 4 if (jQuery.isArray(obj)) { 5 // Serialize array item. 6 jQuery.each(obj, function(i, v) { 7 if (traditional || rbracket.test(prefix)) { 8 // Treat each array item as a scalar. 9 add(prefix, v); 10 11 } else { 12 // If array item is non-scalar (array or object), encode its 13 // numeric index to resolve deserialization ambiguity issues. 14 // Note that rack (as of 1.0.0) can‘t currently deserialize 15 // nested arrays properly, and attempting to do so may cause 16 // a server error. Possible fixes are to modify rack‘s 17 // deserialization algorithm or to provide an option or flag 18 // to force array serialization to be shallow. 19 20 //ytx 20130411 21 buildParams(prefix, v, traditional, add); 22 //buildParams(prefix + "[" + (typeof v === "object" ? i : "") + "]", v, traditional, add); 23 } 24 }); 25 26 } else if (!traditional && jQuery.type(obj) === "object") { 27 // Serialize object item. 28 for (name in obj) { 29 buildParams(prefix + "[" + name + "]", obj[name], traditional, add); 30 } 31 32 } else { 33 // Serialize scalar item. 34 add(prefix, obj); 35 } 36 }
结论:
出问题的代码在22行,我修改成21行那样就行了.
不过,我对js/jquery都是一知半解的,希望不要引起别的后遗症,呵呵.
以上是关于jquery中通过ajax调用webservice传递数组参数的问题的主要内容,如果未能解决你的问题,请参考以下文章