0

我想使用 javascript 调用休息服务。我的代码是:

function CreateXMLHttpRequest() {
   if (typeof XMLHttpRequest != "undefined") {
      alert("1");
      return new XMLHttpRequest();
   }
   else if (typeof ActiveXObject != "undefined") {
      alert("2");
      return new ActiveXObject("Microsoft.XMLHTTP");
   }
   else {
      throw new Error("XMLHttpRequestnot supported");
   }
}

function CallWebService() {
   var objXMLHttpRequest = null;
   objXMLHttpRequest = CreateXMLHttpRequest();

   objXMLHttpRequest.open("POST", "http://localhost:2546/abc.svc/json/GetXml", true);
   objXMLHttpRequest.setRequestHeader("Content-Type", "application/xml;charset=UTF-16");
   var packet = '<CompanyRequest xmlns="http://schemas.datacontract.org/2004/07/abc.DomainModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><CompanyName>company</CompanyName></CompanyRequest>';

   objXMLHttpRequest.send(packet);
      alert(packet);
      var d =(objXMLHttpRequest.responseText);
      alert(d);           
   }

它在 IE 中运行良好,但在 Firefox 和 chrome 中响应为空。我不明白出了什么问题。我一直在寻找这个3天。让我知道是否有任何错误。

提前致谢....

4

2 回答 2

1

您正在进行异步调用。尝试使用回调。

function CreateXMLHttpRequest() {
     if (typeof XMLHttpRequest != "undefined") {
         return new XMLHttpRequest();
     } else if (typeof ActiveXObject != "undefined") {
         return new ActiveXObject("Microsoft.XMLHTTP");
     } else {
         throw new Error("XMLHttpRequestnot supported");
     }
 }
 function CallWebService() {
     var objXMLHttpRequest = CreateXMLHttpRequest();
     objXMLHttpRequest.open("POST", "http://localhost:2546/abc.svc/json/GetXml", true);
     objXMLHttpRequest.setRequestHeader("Content-Type", "text/xml");
     var packet = '<CompanyRequest xmlns="http://schemas.datacontract.org/2004/07/abc.DomainModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><CompanyName>company</CompanyName></CompanyRequest>';
     objXMLHttpRequest.onreadystatechange = function (){
         if (objXMLHttpRequest.readyState==4 && objXMLHttpRequest.status==200) {
             alert(objXMLHttpRequest.responseText);
         }
     }
     objXMLHttpRequest.send(packet);
 }
于 2012-11-21T08:00:32.457 回答
0

您正在执行异步请求。

尝试做一个同步请求,比如

 objXMLHttpRequest.open("POST", "http://localhost:2546/abc.svc/json/GetXml", false);

或异步

objXMLHttpRequest.onreadystatechange = function () {
    if ( objXMLHttpRequest.readyState == 4 ) {
        alert(req.responseText);
    }
};

并将标题设置为:

尝试这个:

 objXMLHttpRequest.setRequestHeader("Content-Type", "text/xml");

 objXMLHttpRequest.setRequestHeader( "SOAPAction", "http://localhost:2546/abc.svc/json/GetXml" );
于 2012-11-21T07:59:54.770 回答