+ -
当前位置:首页 → 问答吧 → 诚请指点js调用webservice问题。

诚请指点js调用webservice问题。

时间:2010-09-25

来源:互联网

服务代码:
[WebService(Namespace = "http://www.51arm.net/")]
public class DataService : System.Web.Services.WebService {
  public DataService() { //InitializeComponent(); }
  [WebMethod]
  public string HelloWorld(){ return "Hello World"; }
  ...
}

服务测试位置:http://www.51arm.net/power485/DataService.asmx?op=HelloWorld

我的js代码:
var xmlhttp; //XMLHttpRequest对象
function myInit()
{
  xmlhttp = null;
  if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  alert("new."); //我的浏览器IE8返回这个
  }
  else if (window.ActiveXObject)
  {// code for IE5 and IE6
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  alert("old.");
  }
  else
  {
  alert("Your browser does not support XMLHTTP.");
  alert("err.");
  }
  return xmlhttp;
}

//具体测试函数
function getWebService()
{
  var request = myInit();
  request.open("POST", "http://www.51arm.net/power485/DataService.asmx/HelloWorld", false); 
  //alert("00"); //这句执行成功
  request.SetRequestHeader("Content-Type","text/xml; charset=utf-8");
  alert("01");//问题1:这句为什么无法执行成功?
  request.SetRequestHeader("Content-Length","0"); //问题2:Content-Length该怎么填写?HelloWorld没有输入函数是否写0?
  alert("02"); //无法到达
  request.SetRequestHeader("SOAPAction",'"http://www.51arm.net/HelloWorld"');
  alert("03"); //无法到达

  var data;
  data = ' <?xml version="1.0" encoding="utf-8"?>';
  data = data + ' <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/">';
  data = data + ' <soap:Body>';
  data = data + ' <HelloWorld xmlns="http://www.51arm.net/">';
  data = data + ' </HelloWorld>';
  data = data + ' </soap:Body>';
  data = data + ' </soap:Envelope>';
  alert(data);

  request.onreadystatechange=function()
  {
  if (request.readyState==4)
  {  
  if(request.status ==200)
  {
  alert( request.responseText);
  }  
  else
  alert(3);
  }
  else
  alert(4);
  }

  request.send(data);
   
}

作者: zhangxuyu1118   发布时间: 2010-09-25

改成这样就可以了。郁闷!
function myInit()
{
  xmlhttp = null;
 if (window.ActiveXObject)
  {// code for IE5 and IE6
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  alert("old.");
  }
  else
  {
  alert("Your browser does not support XMLHTTP.");
  alert("err.");
  }
  return xmlhttp;
}

作者: zhangxuyu1118   发布时间: 2010-09-26

有标准代码
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

作者: icy_csdn   发布时间: 2010-09-26

还有,open方法好象还存在权限问题,test.html单独打开没问题,在http://localhost/test.html打开就不行,是跨域的原因吗。

作者: zhangxuyu1118   发布时间: 2010-09-26