我仔细看看了看看几个人的例子,发现了问题。众所周知webservice是遵守soap协议的,为什么例子都是json格式的参数传递?net webservice兼容json格式,而java的是标准webservice,不兼容json。看来net害了大家啊。于是我仔细了解了wsdl文件,做了个例子。下面只放关键代码。
$(function () {
$("#btnws").click(btnajaxpost);
});
function btnajaxpost(event) {
$.ajax({
type: "post",
contenttype:"text/xml",
url:"http://*****/webservicetest/services/helloworldservice",
data:getpostdata(),//这里不该用json格式
datatype:'xml',//这里设成xml或者不设。设成json格式会让返回值变成null
success: function(xml) {
//对结果做xml解析。
//浏览器判断 (ie和非ie完全不同)
if($.browser.msie){
$("#result").append(xml.getelementsbytagname("ns1:out")[0].childnodes[0].nodevalue+"<br/>");
}
else{
$(xml).find("out").each(function(){
$("#result").append($(this).text()+"<br/>");
})
}
},
error: function(x, e) {
alert('error:'+x.responsetext);
},
complete: function(x) {
//alert('complete:'+x.responsetext);
}
});
}
//定义满足soap协议的参数。
function getpostdata()
{
//根据wsdl分析sayhelloworld是方法名,parameters是传入参数名
var postdata="<?xml version=\"1.0\" encoding=\"utf-8\"?>";
postdata+="<soap:envelope xmlns:xsi=\"http://www.w3.org/2001/xmlschema-instance\" xmlns:xsd=\"http://www.w3.org/2001/xmlschema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
postdata+="<soap:body><sayhelloworld xmlns=\"http://tempuri.org/\">";
postdata+="<parameters>"+$("#txtname").val()+"</parameters>";
postdata+="</sayhelloworld></soap:body>";
postdata+="</soap:envelope>";
return postdata;
}
更多基于jquery的访问webservice的代码(可访问java[xfire])。