簡體   English   中英

純JavaScript調用ASP .NET WebService返回0

[英]Pure JavaScript call ASP .NET WebService returns 0

我實現了一個簡單的ASP.NET WebService,然后嘗試執行功能並獲取返回數據。 但是,ajax調用始終返回狀態0和responseText'undefined'。

我將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
    }
}

我找到了解決方案。 我在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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM