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");
}
});
对应后端的Webservice处理代码如下:
[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);
}
}
最终结论如下:
出错代码位于第22行,将其修改为第21行的处理方式即可解决问题。
由于笔者对JavaScript和jQuery的理解尚不深入,此举可能会引发其他潜在副作用,仅供参考。
以上内容介绍了jQuery中通过ajax调用webservice传递数组参数时遇到的典型问题及解决方法,希望能对大家有所帮助。如有任何疑问,欢迎留言交流,小编会及时回复。感谢大家对本站的支持!