服务器提供了
POST /LoginVerifyWebService/Login.asmx/Login HTTP/1.1
Host: 10.10.10.191
Content-Type: application/x-www-form-urlencoded
Content-Length: length
username=string&password=string&randomString=string
JS代码:
var xmlhttp;
function createXMLHttpRequest(){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
if(window.ActiveXObject)
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("xmlhttp出错");
}
}
function btn_onclick(){
createXMLHttpRequest();
var url="http://10.10.10.191/LoginVerifyWebService/Login.asmx/Login?username=wuhl&password=Wf34566543&randomString=234234";
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange=Response;
xmlhttp.send(null);
}
function Response(){
alert("a"+xmlhttp.readyState);
if(xmlhttp.readyState==4){
alert("xmlhttp.status="+xmlhttp.status);
if(xmlhttp.status==200){
alert("c"+xmlhttp.readyState);
var domObj=xmlhttp.responsetext;
var messageNodes=domObj.getElementsByTagName("Result");
alert(messageNodes.firstChild.nodeValue);
}else{
alert("请求出错");
}
}
}
</script>
您的代码在使用XMLHttpRequest对象发起一个GET请求来访问Web服务,并在返回的响应中查找元素。
从服务器端的提供的接口中看,服务器需要的请求方式是 POST,并且需要传入Content-Type: application/x-www-form-urlencoded格式的参数。
但是您的代码中使用的却是GET请求和没有传入Content-Type参数。
为了解决这个问题,您需要更改代码中的请求方式为POST,并且设置Content-Type和Content-Length。
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var data = "username=wuhl&password=Wf34566543&randomString=234234";
xmlhttp.setRequestHeader("Content-Length", data.length);
xmlhttp.onreadystatechange=response;
xmlhttp.send(data);
这样修改之后会符合服务器的要求,访问结果应该就可以正常了。