jQuery AJAX call to an ASP.NET WebMethod

ε祈祈猫儿з 提交于 2019-11-26 07:46:51

问题


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.


回答1:


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.




回答2:


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



回答3:


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'. :)



来源:https://stackoverflow.com/questions/7770679/jquery-ajax-call-to-an-asp-net-webmethod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!