【问题标题】:Call WebService from Java script从 Javascript 调用 WebService
【发布时间】:2015-11-02 16:20:52
【问题描述】:

我有简单的网络服务:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

    namespace fmNVBwebSrv
    {
        /// <summary>
        /// Summary description for fm
        /// </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 fm : System.Web.Services.WebService
        {

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

我正在尝试从 javaScript 中调用它:

<head runat="server">
<title>Web Service call from client-side JavaScript</title>
<script language="javascript" type="text/javascript">
function SendRequest() 
{
    fm.HelloWorld(form1.MyTextBox.value, OnComplete, OnError,
    OnTimeOut);
}
function OnComplete(arg)
{
    alert(arg);
}
function OnTimeOut(arg)
{
    alert("timeOut has occured");
}
function OnError(arg)
{
    alert("error has occured: " + arg._message);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="http://localhost:55661/fm.asmx" />
</Services>
</asp:ScriptManager>
<div>
<input type="text" value="" id="MyTextBox" />
<input type="button" value="Send Request to the Web Service" 
       id="RequestButton" onclick="return SendRequest()" />
</div>
</form>
</body>

我在控制台Uncaught ReferenceError: fm is not defined 中遇到错误。我是 Java Script 的新手。那里缺少什么?

【问题讨论】:

  • @haraman 这不是一个好的复制品,因为这个问题不适用于 ASP.Net。虽然答案也适用于 AS.Net,但 OP 可能对调用 Web 服务的 ASP.Net 方式更感兴趣。
  • 我认为web方法需要是静态的。
  • @JohnPaul 不,它不需要是静态的。有关 Microsoft 的完整示例,请参阅我的答案中的链接。

标签: javascript asp.net web-services


【解决方案1】:

我遇到了同样的问题并解决了。调用方法时需要添加命名空间:

function SendRequest() 
{
    fmNVBwebSrv.fm.HelloWorld(form1.MyTextBox.value, OnComplete, OnError,
    OnTimeOut);
}

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    你不能像这样直接从 JavaScript 调用 fm,因为 JavaScript 对你的 web 服务一无所知,所以你必须告诉 JavaScript 做什么。检查此Microsoft page for a walkthrough。试试这个:

    <head runat="server">
    <title>Web Service call from client-side JavaScript</title>
    <script language="javascript" type="text/javascript">
    var helloWorldProxy;
    
    // Initializes global and proxy default variables.
    function pageLoad()
    {
        // Instantiate the service proxy.
        helloWorldProxy = new fmNVBwebSrv.fm();
    
        // Set the default call back functions.
        helloWorldProxy.set_defaultSucceededCallback(SucceededCallback);
        helloWorldProxy.set_defaultFailedCallback(FailedCallback);
    }
    
    
    // Processes the button click and calls
    // the service Greetings method.  
    function SendRequest()
    {
        var HelloWorld = helloWorldProxy.HelloWorld();
    }
    
    // Callback function that
    // processes the service return value.
    function SucceededCallback(result)
    {
        var RsltElem = document.getElementById("Results");
        RsltElem.innerHTML = result;
    }
    
    // Callback function invoked when a call to 
    // the  service methods fails.
    function FailedCallback(error, userContext, methodName) 
    {
        if(error !== null) 
        {
            var RsltElem = document.getElementById("Results");
    
            RsltElem.innerHTML = "An error occurred: " + 
                error.get_message();
        }
    }
    
    if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
    </script>
    </head>
    <body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
    <asp:ServiceReference Path="http://localhost:55661/fm.asmx" />
    </Services>
    </asp:ScriptManager>
    <div>
    <input type="text" value="" id="MyTextBox" />
    <input type="button" value="Send Request to the Web Service" 
           id="RequestButton" onclick="SendRequest()" />
    </div>
    </form>
    <script language="javascript" type="text/javascript">
    pageLoad();
    </script>
    </body>
    

    上面这段代码,我在aspx页面中加入了JavaScript,最后调用了pageLoad()函数。我这样做只是为了保持它在你的问题中的方式。但是,最好遵循 MSDN 示例,将 JavaScript 文件保存到 HelloWorld.js 文件中,然后在您的 aspx 文件中引用它,如下所示:

    <asp:ScriptManager runat="server" ID="scriptManager">
        <Services>
            <asp:ServiceReference path="~/fm.asmx" />
        </Services>
        <Scripts>
            <asp:ScriptReference Path="~/HelloWorld.js" />
        </Scripts>
    </asp:ScriptManager>
    

    【讨论】:

    • 我在 var HelloWorld = helloWorldProxy.HelloWorld(); 行中遇到错误未捕获的“TypeError: Cannot read property 'HelloWorld' of undefined”;
    • 也许您需要将 JavaScript 保存到 .js 文件中,并将 &lt;Scripts&gt;&lt;asp:ScriptReference Path="~/HelloWorld.js" /&gt;&lt;/Scripts&gt; 添加到您的 &lt;asp:ScriptManager&gt; 中,就像 MSDN 中的示例一样。或者,您可能可以手动调用pageLoad()。我将更新我的答案以表明这一点。
    • 现在我在“helloWorldProxy = new fmNVBwebSrv.fm();”行中有错误未捕获“ReferenceError: fmNVBwebSrv is not defined”
    • 就像我说的,您最好将脚本保存到 .js 文件中,例如 MSDN 示例。要考虑的事情太多了,所以要让脚本像你想要的那样在标题中工作并不容易。如果您仍然想尝试,如果您将其移至页面末尾并删除我对pageLoad() 函数的调用,也许它会起作用。
    【解决方案3】:

    检查web.config中的key,设置mode = "none"。这解决了我的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      • 2011-05-05
      • 2011-09-06
      • 2013-05-11
      • 2013-12-30
      相关资源
      最近更新 更多