sancoma
sancoma

Reputation: 11

Get JSON via javascript [Cross-Domain]

Please help me with the following situation:

there is the page p1.aspx with only one button:

<button id="btn1" onclick="btnclick();">Button</button>    
<script type="text/javascript">
  $('#btn1').click(function () {
    $.getJSON("http://localhost/p2.aspx", function (data) {
      $.each(data, function (i, field) {            
        alert(field);
      });
    });
  });
</script>

Above is how I want to get the JSON text via javascript.

Web application http://localhost/p2.aspx is redirected to http://localhost/p3.aspx inside. And the page http://localhost/p3.aspx again is redirected back to http://localhost/p2.aspx?code=1.

code=1

is the value I want read in my javascript code. But it's not works.

In p2.aspx I generate JSON data as following

Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonString);
Response.End();

After this I can not read json data via javascript. But if I just put the http://localhost/p2.aspx via web browser then it get json data on the page.

Upvotes: 0

Views: 222

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

You need to use JSONP if you want that to work.

So your script should take into account the callback parameter:

Response.Clear();
string callback = Request["callback"];
if (!string.IsNullOrEmpty(callback))
{
    Response.ContentType = "application/javascript; charset=utf-8";
    Response.Write(string.Format("{0}({1})", callback, jsonString));
}
else
{
    Response.ContentType = "application/json; charset=utf-8";
    Response.Write(jsonString);
}
Response.End();

And then on the client:

$.getJSON("http://localhost/p2.aspx?callback=?", function (data) {
    ...
});

Notice how the callback query string parameter is set to ?. Basically jQuery will translate this to a request that looks like this:

http://localhost/p2.aspx?callback=jQuery123456789....

and your server side script should of course return JSONP which is your JSON string wrapped into the callback name:

jQuery123456789....({"code":1})

Also make sure that the jsonString variable used in your code is an actual JSON string (as its name suggests). Because what you have shown in your question (code=1) is very far from being JSON.

Upvotes: 3

Related Questions