javascript - 从 Javascript 调用 WebService

标签 javascript asp.net web-services

我有简单的网络服务:

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 未定义。我是 Java 脚本新手。那里缺少什么?

最佳答案

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

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

希望这会有所帮助!

关于javascript - 从 Javascript 调用 WebService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33482190/

相关文章:

javascript - 使用jquery获取所有文本节点

c# - 如何在网页中播放音频声音作为背景音乐

c# - 如何不序列化 JSON 对象的 __type 属性

web-services - 在哪里可以找到免费的公共(public) Web 服务?

.net - 尝试将 Android 应用程序连接到 .NET ".svc"Web 服务和服务器响应不支持媒体类型

javascript - 在 WordPress 中集成 JavaScript

javascript - 每次事件后创建目录

asp.net - 如何从 asmx 网络服务返回纯 XML?

xml - 如何在 REST 中传递复杂的查询?

javascript - Dropbox 提供的浏览器缓存图像