如何在 JavaScript 中调用 ASP.Net Web 服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4106026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:23:18  来源:igfitidea点击:

How to call an ASP.Net Web Service in javascript

javascriptasp.netweb-services

提问by Simon Kérouack

As the title states, I'm trying to call a web service written in ASP.Net (Same solution, but different project in visual studio) from javascript. Since I added the web reference for the service prior to this for calling it in VB.Net, I tried to use this reference by directly calling it.

正如标题所述,我试图从 javascript 调用用 ASP.Net 编写的 Web 服务(相同的解决方案,但 Visual Studio 中的项目不同)。由于我在此之前添加了该服务的 Web 引用以在 VB.Net 中调用它,因此我尝试通过直接调用来使用该引用。

In the body of the Default.aspx page, I have this code:

在 Default.aspx 页面的正文中,我有以下代码:

<asp:ScriptManager id="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/App_WebReferences/localhost/ServiceName.discomap" InlineScript="true" />
</Services>
</asp:ScriptManager>

but in javascript, I can't call my service at all. Could anyone explain me how? I'd want to do something like this:

但在 javascript 中,我根本无法调用我的服务。谁能解释我怎么做?我想做这样的事情:

<script type="text/javascript">
 alert(ServiceName.HelloWorld())
</script>

采纳答案by Simon Kérouack

Finally found what I think is the right way to do it, it doesn't need jQuery at all, nor httprequest or any weird workaround. Here's the related code:

终于找到了我认为正确的方法,它根本不需要 jQuery,也不需要 httprequest 或任何奇怪的解决方法。这是相关的代码:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="WebService.asmx/js" type="text/javascript"></script>
    <script type="text/javascript">
        function callback(msg) {
            alert(msg);
        };

        function HelloWorld() {
            WebService.HelloWorld(callback);
        };
    </script>
    <title></title>
</head>
<body>
    <div id="test" onclick="HelloWorld();">
        click this
    </div>

    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
      <Services>
        <asp:ServiceReference Path="~/WebService.asmx" />
      </Services>
    </asp:ScriptManager>
    </form>
</body>
</html>