开发者

How to handle jSON XMLHttpRequest response?

I'm trying to control the json response I send back to the client but didnt know exactly how.. Here is a simple demo:

js code

xhr = new XMLHttpRequest();
xhr.open("POST", "page.aspx", true);
xhr.send();

// handle the response with xhr.responseText

.cs code

    bool success = false;
    string message = String.Empty;

    // Create JSON Response
    var jsonData = new
    {
        success = success,
        message = message
    };

    Response.Write(jsonData);    

The problem is that when I look on the xh开发者_如何学Cr.responseText I see:

"{ success = False, message = } 
<!DOCTYPE html PUBLIC ....
....
..
"


You want to do Response.Clear() and then Response.End() after writing the jsonData.

Then you'll need to handle the JSON response in javascript. I recommend Crockford's JSON library.

I also recommend using jQuery's $.ajax() function rather than hand-rolling your own XHR calls.

PS. Ajax calls would be better made to either ASHX resources or PageMethods/WebMethods declared on your ASPX page. Better still, abandon webforms and use ASP.NET MVC with JsonResults returned from your Controller.

PPS. If you do end up using WebMethods, this article is excellent.


You need to Response.Clear() to clear the response before Response.Write


Your cs code is not generating valid JSON (in addition to it displaying other things after the JSON data). All JSON descriptors must be double quoted, and so must any string values. Values are separated from their descriptors by colons. Example: {"success": false, "message": "It didn't work"}.

Have a look at http://json.org/ for libraries to use with specific languages.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜