jQuery的AJAX调用一个ASP.NET的WebMethod [英] jQuery AJAX call to an ASP.NET WebMethod

查看:108
本文介绍了jQuery的AJAX调用一个ASP.NET的WebMethod的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的jQuery 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);
}

和相应的ASP.NET的WebMethod:

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;
}

这都习惯用异步:假正常工作,不过我必须摆脱它,因为它冻结浏览器,直到接收到响应。现在AJAX请求上述返回未定义。

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?

感谢。

推荐答案

您真的应该确保正确连接$ C C此JSON $。 JSON.stringify 是最可靠的方法:

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

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

这保证了即使 code 网​​址变量包含一些危险人物会破坏你的在生成的JSON在结束一切字符串连接将是正确的连接codeD。该JSON.stringify方法natievly建成现代的浏览器,但如果你需要支持旧的,你可以包括 json2.js

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.

此外,因为你code是不再阻塞,你应该确保,如果你把这个 sendUpdate 一些按钮点击或表单提交取消默认的行动返回false。

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.

这篇关于jQuery的AJAX调用一个ASP.NET的WebMethod的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆