在 ASP.NET WebForms 中使用 jQuery 调用“WebMethod”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6928533/
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-08-26 21:34:52  来源:igfitidea点击:

Calling a 'WebMethod' with jQuery in ASP.NET WebForms

jqueryasp.netajaxwebformswebmethod

提问by marknery

I've set a breakpoint in the following WebMethodbut I'm never hitting the breakpoint.

我在下面设置了一个断点,WebMethod但我从来没有碰到过断点。

cs:

CS:

[WebMethod]
public static string search()
{
    return "worked";
}

aspx:

ASP:

  function search() {
    $.ajax({
        type: "POST",
        url: "ProcessAudit/req_brws.aspx/search",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            alert(msg)
        }
    });
}
<button id = "btnSearch" onclick = "search()" >Search</button>

回答by Darin Dimitrov

Make sure that you have enabled page methods in your ScriptManagerelement:

确保您在ScriptManager元素中启用了页面方法:

<asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />

and that you have canceled the default action of the button by returning false inside the onclick handler, otherwise the page performs a full postback and your AJAX call might never have the time to finish. Here's a full working example:

并且您已经通过在 onclick 处理程序中返回 false 取消了按钮的默认操作,否则页面会执行完整的回发并且您的 AJAX 调用可能永远没有时间完成。这是一个完整的工作示例:

<%@ Page Language="C#" %>
<script type="text/c#" runat="server">
[System.Web.Services.WebMethod]
public static string search()
{
    return "worked";
}
</script>

<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="Form1" runat="server">
        <asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />
        <button id="btnSearch" onclick="search(); return false;" >Search</button>
    </form>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <script type="text/javascript">
        function search() {
            $.ajax({
                type: 'POST',
                url: '<%= ResolveUrl("~/default.aspx/search") %>',
                data: '{ }',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (msg) {
                    alert(msg.d)
                }
            });
        }
    </script>
</body>
</html>

Another possibility is to subscribe to the click handler unobtrusively:

另一种可能性是不显眼地订阅点击处理程序:

<button id="btnSearch">Search</button>

and then inside a separate javascript file:

然后在一个单独的 javascript 文件中:

$('#btnSearch').click(function() {
    $.ajax({
        type: 'POST',
        url: '<%= ResolveUrl("~/default.aspx/search") %>',
        data: '{ }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            alert(msg.d)
        }
    });
    return false;
});

You might also notice the usage of the msg.dproperty inside the success callback which ASP.NET uses to wrap the entire response into as well as the usage of the ResolveUrlmethod to properly generate the url to the page method instead of hardcoding it.

您可能还会注意到msg.dASP.NET 用于将整个响应包装到其中的成功回调中属性的使用,以及使用该ResolveUrl方法正确生成页面方法的 url 而不是对其进行硬编码。

回答by naveen

A more optimised call will be

更优化的调用将是

function search() {
    $.ajax({
        type: "POST",
        url: '<%= ResolveUrl("~/ProcessAudit/req_brws.aspx/search") %>',
        data: "{}",
        contentType: "application/json",
        success: function (msg) {
            msg = msg.hasOwnProperty("d") ? msg.d : msg;
            alert(msg);
        }
    });
}

No need to provide a asp:ScriptManagerat all.

asp:ScriptManager根本不需要提供。

Resource: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

资源:http: //encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

回答by HeavyMerlin

Your current button is causing a full postback. Simply add a type="button" to your button to avoid this.

您当前的按钮导致完整回发。只需在按钮上添加一个 type="button" 即可避免这种情况。

 <button id = "btnSearch" type="button" onclick = "search()" >Search</button>

-Shazzam yo

-沙赞哟

回答by user1694660

How to implement ASP.Net web method using JQuery AJAX ?

如何使用 JQuery AJAX 实现 ASP.Net Web 方法?

HTML Page:

HTML页面:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

    <title></title>
    <script src="js/jquery.min.js"></script>
    <script>
        function SubmitData() {

            var name = 'Ram';
            var gender = 'Male';
            var age = '30';           

            $.ajax({
                type: "POST",
                url: "ajaxcall.aspx/SaveData",
                data: '{"name":"' + name + '", "gender":"' + gender + '", "age":"' + age + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                beforeSend: function () {
                    $('#loader').show();
                },
                success: function (data) {

                    alert(data.d);
                    $('#loader').hide();
                },
                error: function (msg) {
                    //alert('3');
                    msg = "There is an error";
                    alert(msg);
                    $('#loader').hide();
                }
            });

        }
    </script>
</head>
<body>
    <div id="loader" style="display: none;">
        <img src="ajax-loader.gif" />
    </div>
    <a href="#" onclick="SubmitData();">Submit</a>
</body>
</html>

Code behind:

后面的代码:

[WebMethod]
    public static string SaveData(string name, string gender, string age) {
    try {
        return "OK";
    } catch (Exception ex) {
        return ex.Message;
    } finally { }
}

Resource: http://www.sharepointcafe.net/2016/10/how-to-call-aspnet-web-method-using-jquery-ajax.html

资源:http: //www.sharepointcafe.net/2016/10/how-to-call-aspnet-web-method-using-jquery-ajax.html