1

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 xhr.responseText I see:

"{ success = False, message = } 
<!DOCTYPE html PUBLIC ....
....
..
"
Nir
  • 2,497
  • 9
  • 42
  • 71

3 Answers3

0

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

DavidGouge
  • 4,583
  • 6
  • 34
  • 46
0

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.

James McCormack
  • 9,217
  • 3
  • 47
  • 57
  • the clear alone didnt work, with end it did the trick. my response only contains success and message - do I realy need library for that? and abandon webforms just because of what you saw here? – Nir Apr 21 '11 at 14:55
  • In that case, you can vote up my answer and mark it correct :) you don't necessarily have to give up webforms, but I do recommend using existing libraries. Stand on the shoulders of giants - they've undoubtably solved problems you're not even aware of yet :) – James McCormack Apr 21 '11 at 15:00
0

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.

James
  • 20,957
  • 5
  • 26
  • 41