【问题标题】:Calling webservice with Ajax Jquery in asp.net在 asp.net 中使用 Ajax Jquery 调用 web 服务
【发布时间】:2017-09-23 12:30:24
【问题描述】:

我有一个要求,我需要使用 jQuery AJAX 调用来调用 Web 服务。为此,我创建了WebService 并创建了一个客户网站。不幸的是,我无法调用它。 AJAX 调用根本没有触发。

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
  public WebService()
  {   
    //Uncomment the following line if using designed components 
    //InitializeComponent(); 
  }

  [WebMethod]
  public string getMessage(string name)
  {
    return "Hello " + name;
  }
}
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="GetMessage" Style="height: 26px"/>
<asp:Label ID="Label1" runat="server" Font-Bold="True"></asp:Label>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>.
$(document).ready(function () {
  $('#Button1').click(function () {
    alert(1);

    $.ajax({
      type: 'post',
      CORS: true,
      url: 'http://localhost/WebService/Hello.asmx?op=getMessage',
      contentType: "application/xml",
      data: { name: 'aa' },
      success: function (d) {
        alert(d);
      },
      failure: function (response) {
        debugger;
        alert(response.d);
      }
    });
  });
});

我正在尝试从客户端应用程序访问 Web 服务。我正在 URL 路径中传递 ASMX 文件。我也提供了服务参考。不幸的是,它没有触发。 AJAX有什么错误吗?有人可以帮忙吗?它没有显示任何错误。

【问题讨论】:

  • 我不这么认为,CORSJquery.ajax 中有可用选项,但crossDomain 有选项
  • 你能解释一下它到底是什么..
  • Jquery AJAX中没有CORS: true,这样的设置。
  • 是的。我也这样做了..

标签: jquery asp.net ajax web-services asp.net-web-api


【解决方案1】:

编辑:

为了完整和证明,我创建了一个git repository of this solution 并上传到GitHub。您可以clone or download 源代码,在 Visual Studio 2012(或 +)中打开它,然后按 F5 运行它以验证解决方案是否正常工作。您可以根据需要进行修改。


原答案:

我希望您使用的是 jQuery 参考,因为您在问题中错过了它。下面给出的是使用 jQuery 在 ASP.NET 中使用 WebService 代码的工作解决方案。

请使用相对路径,这样如果您在开发或部署中运行应用程序,它就不会给您带来问题。其次,目前您只是选择 asp.net 控件 ID,因为我知道当您将代码移动到子页面的控件时,这会导致您以后出现问题。所以使用 jQuery 选择器类似:$("[id*=Button1]") 来正确选择元素。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("[id*=Button1]").click(function () {
            var message = $("[id*=TextBox1]").val();

            $.ajax({
                type: "POST",
                url: "WebService.asmx/getMessage",
                data: "{ name: '" + message + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    alert(r.d);
                },
                error: function (r) {
                    alert(r.responseText);
                },
                failure: function (r) {
                    alert(r.responseText);
                }
            });
            return false;
        });
    });
</script>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="GetMessage" Style="height: 26px"/>
<asp:Label ID="Label1" runat="server" Font-Bold="True"></asp:Label>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

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

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 WebService : System.Web.Services.WebService
{

    public WebService()
    {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string getMessage(string name)
    {
        return "Hello " + name;
    }
}

输出:

回应:

【讨论】:

  • XMLHttpRequest 无法加载 localhost:55308/WebService.asmx?op=getMessage。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'localhost'。
  • 项目未加载到我的机器中。我已经实现了上面的代码。但我收到类似未定义的错误...
  • 好的。如果您使用此 url “WebService.asmx/getMessage”,则意味着您的 WebService.asmx 类位于根目录上。因此,请仔细检查您创建 Web 服务的位置。如果它在任何文件夹中,则首先添加文件夹名称/webservice/方法名称。
  • @Meghana 你能告诉我你的项目的文件夹结构吗..
  • 这是由于URL。您必须检查您在项目中创建 web 服务的位置,然后将确切的相对地址传递给 jQuery Ajax 函数,错误就会消失......您只需要确保您的案例中的 URL 是否正确...
【解决方案2】:

这是因为 ASP 按钮 id Button1 在 javascript 中不可用,所以为该按钮添加一个类,例如,

<asp:Button ID="Button1" class="getMessage" runat="server" Text="GetMessage" Style="height: 26px"/>

而在 jQuery 中使用,

$(document).ready(function () {
  $('.getMessage').click(function () { // use getMessage class here
    alert(1);
    $.ajax({
      type: 'post',
      // CORS: true, remove this line there is no settings like CORS
      url: 'http://localhost/WebService/Hello.asmx?op=getMessage',
      contentType: "application/xml",
      data: { name: 'aa' },
      success: function (d) {
        alert(d);
      },
      failure: function (response) {
        debugger;
        alert(response.d);
      }
    });
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-04
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多