首頁 > web前端 > js教程 > 主體

jQuery中透過ajax呼叫webservice傳遞數組參數的問題(圖文教學)

亚连
發布: 2018-05-22 11:54:38
原創
1975 人瀏覽過

本文透過實例給大家詳細介紹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]
public XmlDocument xxx(string name, string [] tags )
{ 
return sth; 
}
登入後複製

總是拋出例外.

問題出現在這裡:

#下面是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)

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);
}
}
登入後複製

上面是我整理給大家的,希望今後會對大家有幫助。

相關文章:

利用ajax傳遞陣列及後台接收的方法詳解

AJAX分頁效果簡單實作(圖文教學)

Ajax傳遞特殊字元的資料如何解決

以上是jQuery中透過ajax呼叫webservice傳遞數組參數的問題(圖文教學)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!