2012-08-05 41 views
0

我試圖調用webservice的asp.net javascript中/ jQuery的, 我已經試過這樣的例子很多,但遺憾的是沒有成功,如何在JavaScript或JQuery中調用SOAP(XML)webservice?

這裏是我目前正試圖代碼,

login("[email protected]", "123456"); 
    var productServiceUrl = 'http://localhost:50575/Service1.asmx?op=test'; // Preferably write this out from server side 

    function login(Email, Password) { 
     var soapMessage = '<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/"> \ 
<soap:Body> \ 
<login xmlns="http://test.com/"> \ 
<Email>' + Email + '</Email> \ 
<Password>' + Password + '</Password> \ 
</login> \ 
</soap:Body> \ 
</soap:Envelope>'; 

     $.ajax({ 
      url: productServiceUrl, 
      type: "GET", 
      dataType: "xml", 
      data: soapMessage, 
      complete: endSaveProduct, 
      error: function (a, b, c) { 
       alert(a + "\n" + b + "\n" + c); 
      }, 
      contentType: "text/xml; charset=\"utf-8\"" 
     }); 

     return false; 
    } 

    function endSaveProduct(xmlHttpRequest, status) { 
     $(xmlHttpRequest.responseXML) 
    .find('loginResult') 
    .each(function() { 
     alert($(this).find('Message').text()); 
    }); 
    } 

請幫我, 在此先感謝。

回答

4

有多種問題:

  • 要發送到不同的域的請求,所以它不會,除非該領域的工作是發送跨源資源共享(CORS)標題Access-Control-Allow-Origin: *或專門讓你的出身
  • 您正在使用GET,因爲您應該使用POST,因爲在SOAP over HTTP中,信封必須位於請求正文中。
  • jQuery始終認爲您的數據是application/x-www-form-urlencoded,除非您將processData設置爲false。只有設置contentType只會使標題處於謊言狀態,並不會真正改變這一點。事實上,如果參數data是一個字符串,則不是這樣。

看來您的目標域不允許CORS,所以不可能直接從客戶端進行。您必須使用服務器代理來執行請求。

如果他們允許CORS,你會做它像這樣:

var soapMessage = '<?xml version="1.0" encoding="utf-8"?>\ 
        <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">\ 
         <soap12:Body>\ 
         <login xmlns="http://tastygo.com/">\ 
          <BBMID>string</BBMID>\ 
          <Email>string</Email>\ 
          <Password>string</Password>\ 
         </login>\ 
         </soap12:Body>\ 
        </soap12:Envelope>'; 

$.ajax("http://m.allaccesstnt.com/AATnTWebservices/Webservices/Userwebservice.asmx", { 

    contentType: "application/soap+xml; charset=utf-8", 
    type: "POST", //important 
    dataType: "xml", 
    data: soapMessage 

}); 

但是,這將不能工作,因爲服務器不允許選項,瀏覽器必須使用來確定一個跨域請求是否是允許:

OPTIONS http://m.allaccesstnt.com/AATnTWebservices/Webservices/Userwebservice.asmx 405 (Method Not Allowed) 

第二個問題是:

XMLHttpRequest cannot load http://m.allaccesstnt.com/AATnTWebservices/Webservices/Userwebservice.asmx. Origin http://stackoverflow.com is not allowed by Access-Control-Allow-Origin. 
+1

所以,你有什麼解決辦法兄弟? – 2012-08-05 12:23:40

+0

你是什麼意思?我剛剛說過,由於同源安全策略,這是不可能的。服務器必須允許使用我無法控制的標題。 – Esailija 2012-08-05 12:24:58

+0

好吧,謝謝:) – 2012-08-05 12:30:47

相關問題