jQuery中通过ajax调用webservice传递数组参数的问题实例详解
下面通过实例给大家说明比较直观些,更方便大家了解。
本人的项目中通过jquery.ajax调用webservice.
客户端代码如下:
$.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"); } });
服务端代码如下:
[WebMethod] publicXmlDocumentxxx(stringname,string[]tags) { returnsth; }
总是抛出异常.
问题出现在这里:
下面是HTTP数据:
POSThttp://xxx.com/xxx.asmx/xxxHTTP/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(WindowsNT5.1)AppleWebKit/535.1(KHTML,likeGecko)Chrome/14.0.835.186Safari/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/xxxHTTP/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)
functionbuildParams(prefix,obj,traditional,add){ varname; if(jQuery.isArray(obj)){ //Serializearrayitem. jQuery.each(obj,function(i,v){ if(traditional||rbracket.test(prefix)){ //Treateacharrayitemasascalar. add(prefix,v); }else{ //Ifarrayitemisnon-scalar(arrayorobject),encodeits //numericindextoresolvedeserializationambiguityissues. //Notethatrack(asof..)can'tcurrentlydeserialize //nestedarraysproperly,andattemptingtodosomaycause //aservererror.Possiblefixesaretomodifyrack's //deserializationalgorithmortoprovideanoptionorflag //toforcearrayserializationtobeshallow. //ytx buildParams(prefix,v,traditional,add); //buildParams(prefix+"["+(typeofv==="object"?i:"")+"]",v,traditional,add); } }); }elseif(!traditional&&jQuery.type(obj)==="object"){ //Serializeobjectitem. for(nameinobj){ buildParams(prefix+"["+name+"]",obj[name],traditional,add); } }else{ //Serializescalaritem. add(prefix,obj); } }
结论:
出问题的代码在22行,我修改成21行那样就行了.
不过,我对js/jquery都是一知半解的,希望不要引起别的后遗症,呵呵.
以上所述是小编给大家介绍的jQuery中通过ajax调用webservice传递数组参数的问题实例详解的相关知识,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!