chrome和firefox中的响应为null

时间:2012-11-21 07:17:36

标签: javascript xml wcf-rest

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

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天。 如果有任何错误,请告诉我。

提前致谢....

2 个答案:

答案 0 :(得分: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);
 }

答案 1 :(得分: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" );