下面通過實例給大家說明比較直觀些,更方便大家瞭解。
本人的項目中通過jquery.ajax調用webservice.
客戶端代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 | $.ajax({ url: "test/xxx.asmx" , type: 'POST' , dataType: 'xml' , timeout: , data: { name: "zhangsan" , tags: [ "aa" , "bb" , "cc" ] }, error: function (xml) { alert(xml.responseText); }, success: function (xml) { alert( "OK" ); } }); |
服務端代碼如下:
1 2 3 4 5 | [WebMethod] public XmlDocument xxx(string name, string [] tags ) { return sth; } |
總是拋出異常.
問題出現在這裏:
下面是HTTP數據:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 |
而它期望的格式是如下的:
1 2 3 4 5 | 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的數據除了問題. 正確的應該如下:
1 | name=zhangsan&tags=aa&tags=bb&tags=cc |
看來問題出在jquery.ajax上面了.見代碼(jquery.1.8.3.js)
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 29 30 31 | function buildParams(prefix, obj, traditional, add) { var name; if (jQuery.isArray(obj)) { // Serialize array item. jQuery.each(obj, function (i, v) { if (traditional || rbracket.test(prefix)) { // Treat each array item as a scalar. add(prefix, v); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of ..) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. //ytx buildParams(prefix, v, traditional, add); //buildParams(prefix + "[" + (typeof v === "object" ? i : "") + "]", v, traditional, add); } }); } else if (!traditional && jQuery.type(obj) === "object" ) { // Serialize object item. for (name in obj) { buildParams(prefix + "[" + name + "]" , obj[name], traditional, add); } } else { // Serialize scalar item. add(prefix, obj); } } |
結論:
出問題的代碼在22行,我修改成21行那樣就行了.
不過,我對js/jquery都是一知半解的,希望不要引起別的後遺症,呵呵.
以上所述是小編給大家介紹的jQuery中通過ajax調用webservice傳遞數組參數的問題實例詳解的相關知識,希望對大家有所幫助。