2017-09-18 76 views
0

我實現了一個簡單的ASP.NET WebService,並嘗試執行函數並獲取返回數據。但是ajax調用總是返回狀態0和responseText'undefined'。純JavaScript調用ASP .NET WebService返回0

我把我的WebService調試模式,我看到哪些數據發送正確,但我沒有回報。

我讀了很多關於return 0的帖子,但是我沒有找到任何解決方法。

有什麼不對嗎?非常感謝!

WebService的代碼:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Linq; 
using System.Web; 
using System.Web.Services; 
using System.Web.Services.Protocols; 
using System.Xml.Linq; 

namespace WebServiceDA 
{ 
    /// <summary> 
    /// Summary description for WebService1 
    /// </summary> 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService] 
    public class WebService1 : System.Web.Services.WebService 
    { 
     //inicialização da estrutura do E3DataAccess 
     E3DATAACCESSLib.E3DataAccessManagerClass E3Da = null; 

     public WebService1() 
     { 
      //inicializa a conexão com o E3DataAccess 
      try 
      { 
       E3Da = new E3DATAACCESSLib.E3DataAccessManagerClass(); 
      } 
      catch(Exception ex) 
      { 
       Console.Write(ex.ToString()); 
      } 
     } 

     [WebMethod] 
     public string HelloWorld() 
     { 
      return "Hello World"; 
     } 

     [WebMethod] 
     public string ReadValue(string ObjectName) 
     { 
      object dt = null, v = null, q = null; 
      if(E3Da.ReadValue("Dados." +ObjectName, ref dt, ref q, ref v)){ 
       return v.ToString(); 
      } 
      return "Invalid Object Name"; 
     } 
    } 
} 

HTML代碼:

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="utf-8"> 
     <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
     <title>WebService with E3DataAccess</title> 

     <script type="text/javascript" src="accessWs.js"></script> 
    </head> 

    <body> 
     <h1> WebService E3DataAccess</h1> 
     <p> Exemplo de um cliente html que acessa métodos de um webservice que contém um E3DataAccess</p> 

     <div style="background-color:#FFFFFF" id="content"> 
      <span>Tag Name:</span> 
      <input type="text" name="tagname" id="tagname"> 
      <input type="button" value="Get Tag Value" onclick="CallWs();" 
     </div> 
    </body> 
</html> 

JavaScript代碼:

var ajax; 

function CreateAjaxObject(){ 
    if(window.XMLHttpRequest){ //navegadores modernos 
     ajax = new XMLHttpRequest(); 
    } 
    else if(window.ActiveXObject){ //IE antigao 
     ajax = new ActiveXObject("Msxml2.XMLHTTP"); 
     if(!ajax){ 
      ajax = new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
    } 
    if(!ajax){ //caso não tenha sido iniciado com sucesso 
     alert("seu navegador não possui suporte"); 
    } 
} 

function SendData(url,dados,AjaxResponseFunction){ 
    CreateAjaxObject(); 
    if(ajax){ 

     //método http 
     ajax.open("POST",url,true); 

     //definir o encode do conteúdo 
     ajax.setRequestHeader('Content-Type',"application/x-www-form-urlencoded"); 

     //tamanho dos dados 
     ajax.setRequestHeader('Content-Length',dados.length); 

     //enviar os dados 
     alert(dados); 
     ajax.send(dados); 

     //retorno 
     ajax.onreadystatechange = function(){ 
      if(ajax.readyState==4){ //documento está pronto 
       alert(ajax.status); 
       AjaxResponseFunction(ajax.status,ajax.ResponseText); 
      } 
     }; 

    } 
} 

function CallWs(){ 
    var dados = ''; 
    dados = 'ObjectName=' + encodeURIComponent(tagname.value); 

    //chamar um webservice = endereço/nomemétodo 
    SendData('http://localhost:53626/WebService.asmx/ReadValue',dados,AjaxResponseFunction); 
} 

function AjaxResponseFunction(status,response){ 
    var divR = document.getElementById('content'); 
    if(ajax.status != 200){ 
     divR.style.backgroundColor = "#FF0000"; //erro vermelho 
    } 
    else{ 
     divR.style.backgroundColor = "#FFFFFF"; //ok branco 
    } 
} 
+0

我會移動'ajax.send(dados);'到事件處理程序分配後('ajax.onreadystatechange') – mplungjan

+0

我嘗試這一點。不起作用。謝謝! – FelipeFonsecabh

回答

-2

我使用Mozilla Firefox瀏覽器的開發模式,我得到這個錯誤:

「Ajax跨源請求被阻止:相同來源策略不允許讀取遠程資源「

我如何在mycode中修復它?我不知道如何使用CORS。

+0

通過提供原始問題的答案,您可以提出更多問題,您應該是谷歌搜索您最初對CORS的理解,網上有很多關於CORS的頁面解釋 –

0

我找到了解決方案。我在Web.config文件中添加一個簡單的代碼:

<system.webServer> 
    <handlers> 
     <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 
     <remove name="OPTIONSVerbHandler" /> 
     <remove name="TRACEVerbHandler" /> 
     <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> 
    </handlers> 

    <!-- bellow, code used to fix the security problem--> 
     <httpProtocol> 
      <customHeaders> 
      <add name="Access-Control-Allow-Origin" value="*" /> 
      </customHeaders> 
     </httpProtocol> 
    <!-- end code --> 

    </system.webServer></configuration>