0

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.

Steve
  • 31,144
  • 19
  • 99
  • 122
sancoma
  • 11
  • 2
  • Try using a relative URL ie just `/p2.aspx` – asawyer Jul 31 '13 at 19:08
  • The cause is that p2.aspx will be placed on my server but p3.aspx and p1.aspx will be placed on foreign servers – sancoma Jul 31 '13 at 19:14
  • What is the value of `jsonString`? – David Rettenbacher Jul 31 '13 at 19:20
  • the value for `jsonstring` is { flag: "1" } just the simple value to try get json object – sancoma Jul 31 '13 at 19:21
  • So your trying to get cross domain json then. Thats the sort of thing you need to mention in your question. You read the *dataType* section here http://api.jquery.com/jQuery.ajax/ – asawyer Jul 31 '13 at 19:25
  • Thanks, I'll try to use crossDomain – sancoma Jul 31 '13 at 19:28
  • It's not working. @asawyer can you please give more information about how I should setup ajax request to use cross domain? – sancoma Jul 31 '13 at 19:44
  • http://stackoverflow.com/questions/2681466/jsonp-with-jquery – asawyer Jul 31 '13 at 19:45
  • @asawyer thanks for link but I have added `?callback=?` to my url and set the following `$.ajaxSetup({ crossDomain: true });` but it doesn't work. – sancoma Jul 31 '13 at 20:04
  • Now there is the following in javascript console `Error: SyntaxError: invalid label Source Code: {"flag":"1"}` – sancoma Jul 31 '13 at 20:09
  • 1
    @sancoma: Using `crossDomain` and/or adding `?callback=?` doesn't magically make it work. You need to make sure the server supports it. If you add `?callback=?`, you're requesting JSONP. This means you should return a JavaScript file (`application/javascript`) using the callback param as a function call: like `$_GET['callback'] . '(' . json_encode($data) . ');'` (I use PHP, adapt to your language). Or use CORS, by setting the `Access-Control-Allow-Origin` header on the server (http://enable-cors.org/) – gen_Eric Jul 31 '13 at 20:25

1 Answers1

3

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • If you are using JSONP, the correct `Content-type` to send with the response should be `application/javascript`. JSONP is actually just a JavaScript file, that's appended to your page. – gen_Eric Jul 31 '13 at 20:26
  • You are perfectly correct. I have updated my answer to reflect this. Thanks for pointing that out. – Darin Dimitrov Jul 31 '13 at 20:27
  • No problem. Some browsers might've got mad about that :-P – gen_Eric Jul 31 '13 at 20:28
  • @DarinDimitrov Have I mentioned lately how much I love you? – asawyer Jul 31 '13 at 20:42
  • @DarinDimitrov Sorry for misprint but I have posted an incorrect scenario how it should works. The correct scenario is: Web application p2.aspx is redirected to p3.aspx inside. And the page p3.aspx again is redirected back to p2.aspx. And into this p2.aspx I generate the JSON data. So I do not provide JSON data in url as a parameter for p2.aspx. – sancoma Jul 31 '13 at 21:56
  • 1
    @sancoma, this doesn't matter. No matter how many redirects you are doing, at the end of the day you should return JSONP as shown in my answer if you want to be able to do cross domain AJAX calls. – Darin Dimitrov Aug 01 '13 at 06:03