在 JS Ajax 调用 CodeBehind 静态函数后动态更新标记

本文关键字:动态 更新 静态函数 JS Ajax 调用 CodeBehind | 更新日期: 2023-09-27 18:30:49

我正在使用$.ajax({...});将一些数据发送到我的服务器(c#中aspx的CodeBehind文件)。为了接收要在代码隐藏文件中处理的数据,我必须使用静态 WebMethod ([System.Web.Services.WebMethod] )。处理完这些数据后,如果成功(在我的情况下,信用卡收费成功),我想将它们重定向到新页面,否则,向用户发送警报,指出出现问题(即,信用卡收费随机不起作用)。

有没有办法通过这个静态 WebMethod 访问/更改当前页面的标记(例如,添加<script>alert("Something went wrong")</script>),而无需使用 asp 页面控件?(即,this这是 CodeBehind 文件中非静态方法中的页面)

在 JS Ajax 调用 CodeBehind 静态函数后动态更新标记

您可能需要使用 $.ajax 语法的"成功与失败"部分。 请参考下面的示例。 我希望您的 web 方法返回字符串以使其正常工作。

示例 WebMeethod

[ScriptMethod()]
    [WebMethod]
    public static string YourWebMethod()
    {
        String yourMessageString = String.Empty;
        //process as per your logic
       yourMessageString = "Some Message";
       return yourMessageString;
    }

$.ajax({
            type: "POST",
            url: "/yourpage.aspx/yourwebmethod",
            async: false,
            contentType: "application/json; charset=utf-8",
            data: "your data",
            dataType: "json",
            success: function (message) {
                alert(message);
            },
            error: function () {
                alert("error");
            },
            failure: function () {
                alert('failure');
            }
        });