jQuery 中通过 ajax 调用 webservice传递数组参数的问题实例详解
本文通过实例给大家详细介绍jQuery中通过ajax调 用webservice传递数组参数的相关资料,需要的朋友可以 参考下
下面通过实例给大家说明比较直观些,更方便大家了
本人的项目中通过jquery. ajax调用webservice.
客户端代码如下:
$. ajax({
url:"test/xxx. asmx〃,
type:’ POS T’,
dataType :, xml’, time out:,
data : {name:”zha ngsarT,tags :『aa' "bb' "cc"]}, err or:function (xml) {
ale rt (xml. resp onseText):
},
success:function(xm 1) {
alert ("0 K");
});
服务端代码如下:
[WebMe thod]
publ icXmlDocume ntxxx(strin gname,strin g口 tags) {nb sp;
returnst h;nbsp;
总是抛出异常.
问题出现在这里:
下面是HTTP数据:
POST. com/x xx. asmx/xxx HTTP/1. 1 H ost: center, cmis. htpc. c Conn ection:keep -alive
Conte nt_Length:5 5
Cache-Co ntrol: max-a ge=O Origi n: x. com
User -Agent:Mozi lla/5. 0(Win dowsNT5. 1)A ppleWebKit/535. 1 (KHTML,likeGecko)
Chrome/14. 0.835. 186Saf ari/535. 1
Content-Typ e:applicati on/x-www-fo rm-urlencod ed;charset=UTF-8
Acce pt :applicat ion/xml, tex t/xml,氺/氺;q =0. 01 Refe rer:. com/xxx . aspx
Acce pt-Encoding :gzip, defla te, sdch
Ac cept-Langua ge: zh-CN, zh : q=0. 8
Acc ept-Charset :GBK, utf-8;q=0. 7,*;q=0 ? 3
name=zh angsanamp;t ags%5B%5D=a aamp;tags%5 B%5D=bbamp: tags°/o5B%5D=cc
而它期望的格式是如下的:
POST/x xx. asmx/xxx HTTP/1. 1
Hos t: xxx. com
Content-Typ e:applicati on/x-www-fo rm-urlencod ed
Content -Length: len gth
name=s tringamp; ta gs=stringam p; tags=stri ng
比较上面粗体,post的数据除了问题.正确的应该如下: name=zhangs anamp; tags=aaamp; tags=bbamp; tags=cc 看来问题出在j query, ajax上面了.见代码(jque
ry. 1. 8. 3. js )
function buildParams (prefix, obj ,traditiona 1,add) {
varn ame;
if (jQ uery. isArra y (obj)) {nbs p;
//Seria lizearrayit em.
jQuery . each (obj, f unction (i,v ) {
if (trad itional | | rb racket, test (prefix)) {n bsp; //Tre ateacharray itemasascal ar.
add (pref ix,v);
}else {
//Ifarra yitemisnon- scalar(arra yorobject), encodeits
//numericin dextoresolv edeserializ ationambigu ityissues.
//Notethat rack(asof. . )can’tcurre ntlydeseria
lize
//nes tedarrayspr operly, anda ttemptingto dosomaycaus e
//aserve rerror. Poss iblefixesar etomodifyra ck’ s//de