首页 > 解决方案 > 无法在没有任何数据的情况下通过 JQuery 调用 ASPX 函数

问题描述

我正在尝试使用 jquery 调用我的 aspx 函数,但我无法调用它。我在我的代码中添加了一个断点,但该断点永远不会关闭,这意味着该函数永远不会被调用。以下是我的代码:

jQuery:

update();

function update() {
    $.ajax({
        url: 'Codes.aspx/testfunction',
        method: 'post',
        success: function () { alert("yay"); },
        failure: function () { alert("no"); }
    });
}

aspx:

public static void testfunction()
{
    // A break point in visual studio here
}

总是调用成功函数,但代码永远不会在断点处中断。

但是,我希望在 aspx 函数中的 db 中填充我的数据。

让我知道我错在哪里。

整个 Jquery 函数:

$(document).ready(function () {
            $("#Add_Code").click(function () {                      //Empty code validation
                var new_code = $("#<%=new_code.ClientID%>").val();
                // alert(new_code);
                if (new_code == "") {
                    $("#validation_code").show();
                    $("#error_div").addClass("has-error");
                }
                else if (new_code != "") {
                    update();

                    function update() {
                        $.ajax({
                            url: "Codes.aspx/testfunction",
                            method: "POST",
                            data: "Sent from update function",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            //async: true,
                            //cache: false,
                            success: function (response) { alert(response.d); },
                            failure: function (response) { alert("no "+response.d); }
                        });
                        return false;
                    }
                }
            })

更新代码:

[WebMethod]
public static string testfunction(string response)
{
    string abc = response;
    return abc + "and server";
}

标签: jqueryasp.netfunctioncall

解决方案


将此粘贴到脚本标记中。添加您的 if 条件以检查空值

<script>

    $(document).ready(function () {
        $("#Add_Code").click(function () {                //Empty code validation

            update();                
            return false;
        });

        });
    function update() {
        var obj = {};
        obj.response = "Sent from update Function";
        $.ajax({
            url: "default2.aspx/testfunction",
            method: "POST",
            data: JSON.stringify(obj),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            //async: true,
            //cache: false,
            success: function (response) { alert(response.d); },
            failure: function (response) { alert("no " + response.d); }
        });
        }

</script>

推荐阅读