对 ASP.NET WebMethod 的 jQuery AJAX 调用

发布于 2024-12-09 15:15:57 字数 1036 浏览 0 评论 0原文

我有以下 jQuery AJAX 请求:

function sendUpdate(urlToSend) {
    var code = AccessCode; 
    var url = urlToSend;
    var options = { error: function(msg) { alert(msg.d); },
                    type: "POST", url: "webmethods.aspx/UpdatePage",
                    data: "{ accessCode: " + code + ", newURL: '" + url + "' }",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: true, 
                    success: function(response) { var results = response.d; } }; 
    $.ajax(options);
}

以及相应的 ASP.NET WebMethod:

[WebMethod]
public static bool UpdatePage(string accessCode, string newURL)
{
    bool result = true;
    try
    {
        HttpContext.Current.Cache[accessCode + "l"] = newURL;
    }
    catch
    {
        result = false;
    }

    return result;
}

所有这些都可以与“async:false”一起正常工作,但是我必须摆脱它,因为它会冻结浏览器,直到收到响应。现在上面的 AJAX 请求返回“未定义”。

有人能告诉我为什么会发生这种情况以及问题出在哪里吗?

谢谢。

I have the following jQuery AJAX request:

function sendUpdate(urlToSend) {
    var code = AccessCode; 
    var url = urlToSend;
    var options = { error: function(msg) { alert(msg.d); },
                    type: "POST", url: "webmethods.aspx/UpdatePage",
                    data: "{ accessCode: " + code + ", newURL: '" + url + "' }",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: true, 
                    success: function(response) { var results = response.d; } }; 
    $.ajax(options);
}

And the corresponding ASP.NET WebMethod:

[WebMethod]
public static bool UpdatePage(string accessCode, string newURL)
{
    bool result = true;
    try
    {
        HttpContext.Current.Cache[accessCode + "l"] = newURL;
    }
    catch
    {
        result = false;
    }

    return result;
}

That all used to work correctly with "async:false", however I have to get rid of it as it freezes the browser until the response is received. Now the AJAX request above returns "undefined".

Could anybody tell me why it happens and where the problem is?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

薯片软お妹 2024-12-16 15:15:57

您确实应该确保正确编码此 JSON。 JSON.stringify 是最可靠的方法:

data: JSON.stringify({ accessCode: code, newURL: url })

这可以确保即使 codeurl 变量包含一些会破坏字符串连接的危险字符在最终生成的 JSON 中,所有内容都将被正确编码。 JSON.stringify 方法自然内置于现代浏览器中,但如果您需要支持旧版,您可以包含 json2.js< /a>.

另外,因为您的代码不再阻塞,所以您应该确保如果您从某个按钮单击或表单提交调用此 sendUpdate ,您可以通过返回 false 来取消默认操作。

You should really make sure to properly encode this JSON. JSON.stringify is the most reliable method:

data: JSON.stringify({ accessCode: code, newURL: url })

This ensures that even if the code and url variables contain some dangerous characters that will break your string concatenations in the resulting JSON at the end everything will be properly encoded. The JSON.stringify method is natievly built into modern browsers but if you need to support legacy you could include json2.js.

Also because you code is no longer blocking you should make sure that if you call this sendUpdate from some button click or form submit you cancel the default action by returning false.

赢得她心 2024-12-16 15:15:57

我的方法工作正常:

[System.Web.Services.WebMethod()] 

        public static string getHello(string str)
        {
            //do some things with str   
            return str;
        }

在文件.js中,我定义这个函数来调用文件.cs中的webmethod:

function CallServerFunction(StrPriUrl, ObjPriData, CallBackFunction) {

    $.ajax({
        type: "post",
        url: StrPriUrl,
        contentType: "application/json; charset=utf-8",
        data: ObjPriData,
        dataType: "json",
        success: function (result) {
            if (CallBackFunction != null && typeof CallBackFunction != 'undefined') {
                CallBackFunction(result);
            }

        },
        error: function (result) {
            alert('error occured');
            alert(result.responseText);
            window.location.href = "FrmError.aspx?Exception=" + result.responseText;
        },
        async: true
    });
}

然后,调用使用(在file.js中调用):

 var text = $("#textbox_send").val();

    var myresult;
    CallServerFunction("Default.aspx/getHello", JSON.stringify({ str: text }), function (myresult) {
        if (text != "")
            $('#' + id).append('<p>' + $("#account_user").text() + ': ' + myresult.d + '</p>');
    });

My way works correctly:

[System.Web.Services.WebMethod()] 

        public static string getHello(string str)
        {
            //do some things with str   
            return str;
        }

In file .js, I define this function to call webmethod in file .cs:

function CallServerFunction(StrPriUrl, ObjPriData, CallBackFunction) {

    $.ajax({
        type: "post",
        url: StrPriUrl,
        contentType: "application/json; charset=utf-8",
        data: ObjPriData,
        dataType: "json",
        success: function (result) {
            if (CallBackFunction != null && typeof CallBackFunction != 'undefined') {
                CallBackFunction(result);
            }

        },
        error: function (result) {
            alert('error occured');
            alert(result.responseText);
            window.location.href = "FrmError.aspx?Exception=" + result.responseText;
        },
        async: true
    });
}

Then, call to use (call in file.js):

 var text = $("#textbox_send").val();

    var myresult;
    CallServerFunction("Default.aspx/getHello", JSON.stringify({ str: text }), function (myresult) {
        if (text != "")
            $('#' + id).append('<p>' + $("#account_user").text() + ': ' + myresult.d + '</p>');
    });
落墨 2024-12-16 15:15:57

“未定义”可能是服务器错误的结果。如果你使用Firebug、Firefox(或任何好的客户端调试工具),你可以找到服务器返回的错误。如果有错误,请粘贴。

尽管如此,我还注意到“accessCode”的“数据”未正确括在引号“”内,

更正后的数据选项将是:

data: "{ accessCode: '" + code + "', newURL: '" + url + "' }",

PS:
由于 'options' 在 Jquery 中具有不同的含义,我建议将变量名称更改为 'setting' 。将“var options”更改为“var settings”。 :)

The "undefined" could be the result of a server error.If you use Firebug,Firefox(or any good client debugging tool), you can find the error returned by the server. Paste the error,if any.

Nevertheless, I also noted the the "data" for "accessCode" is not properly enclosed within quotes ‘ ’

The corrected data option would be :

data: "{ accessCode: '" + code + "', newURL: '" + url + "' }",

PS:
Since 'options' have a different meaning in Jquery, I would recommend changing the variable name as 'setting' . Change 'var options ' to 'var settings'. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文