【问题标题】:MicrosoftAjax.js, SOAP Web Services, and static HTMLMicrosoftAjax.js、SOAP Web 服务和静态 HTML
【发布时间】:2025-12-17 07:30:01
【问题描述】:

如果您只是在静态 HTML 中包含 JavaScript,那么使用 MicrosoftAjax.js 调用 ASMX Web 服务的正确方法是什么?

到目前为止我所拥有的:

<html>
<head>
    <title>Testing</title>
    <script type="text/javascript" src="scripts/MicrosoftAjax.js"></script>
    <script type="text/javascript">
        function testCallSoap() {
            // in here I want to call the default HelloWorld() method
            // it is located at ~/MyTestService.asmx
        }
    </script>
</head>

<body>
    <div>
        <span onclick="testCallSoap();">test</span><br />
    </div>
</body>
</html>

【问题讨论】:

  • 我认为您的意思是“ASMX Web 服务”
  • 注意:另请阅读 InfinitiesLoop 的回答

标签: .net ajax web-services asp.net-ajax asmx


【解决方案1】:

老实说,我从来没有在没有脚本管理器的情况下调用过网络服务,但是:

在您的网络服务中,您需要确保您的网络服务类使用 [ScriptService] 属性。然后你可以包含这个js文件:MyService.asmx/js。

[ScriptService]
public class MyService : WebService
{
    [WebMethod]
    public string Foo()
    {
         return "bar";
    }
}

这将使它与 JSON 一起工作......请参阅这篇文章: http://geekswithblogs.net/JuanDoNeblo/archive/2007/10/24/json_in_aspnetajax_part2.aspx

并不是一个完整的答案,但我希望它能让你朝着正确的方向前进。

【讨论】:

  • +1 我见过这种方法。我想你可以在前几个脚本引用中放入类似的东西 这将引入代理。
【解决方案2】:

你可以使用WebServiceProxy的静态invoke()方法:

Sys.Net.WebServiceProxy.invoke("foo.asmx", "HelloWorld", false, { param: 'foo' }, onSuccess, onFailed);

http://msdn.microsoft.com/en-us/library/bb383814.aspx

路径必须是客户端可用的路径,例如“~/”将不起作用。

【讨论】:

    【解决方案3】:

    如果您已经在使用 Ajax.Net,这就像使用 ScriptManager 注册 WebService 一样简单。这是未经测试的,我只是从记忆中键入它来给你一个想法。

    网络服务:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]
    public class MyTestService: WebService
    {
        [WebMethod(true), ScriptMethod]
        public string DefaultMethod(string msg)
        {
            return "ZOMG HI THERE! You said: " + msg;
        }
    }
    

    调用页面背后的代码

    partial class Test {
        protected void Page_Load(object sender, EventArgs e)
        {
            ScriptManager.GetCurrent(Page).Services.Add(new ServiceReference("~/MyTestService.asmx"));
    
        }
    }
    

    调用页面上的Javascript:

    function testCallSoap() {
       MyTestService.Test("Foobar!", onTestSuccess, onTestFail);
    }
    function onTestSuccess(result) {
       alert(result);
    }
    function onTestFail(result) {
       alert("omg fail!");
       alert(result._message);
    }
    

    【讨论】: