jquery - Get JSON via javascript [Cross-Domain] -


please me following situation:

there page p1.aspx 1 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 how want json text via javascript.

web application http://localhost/p2.aspx redirected http://localhost/p3.aspx inside. , page http://localhost/p3.aspx again redirected http://localhost/p2.aspx?code=1.

code=1 

is value want read in javascript code. it's not works.

in p2.aspx generate json data following

response.clear(); response.contenttype = "application/json; charset=utf-8"; response.write(jsonstring); response.end(); 

after can not read json data via javascript. if put http://localhost/p2.aspx via web browser json data on page.

you need use jsonp if want work.

so script should take account 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 on client:

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

notice how callback query string parameter set ?. jquery translate request looks this:

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

and server side script should of course return jsonp json string wrapped callback name:

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

also make sure jsonstring variable used in code actual json string (as name suggests). because have shown in question (code=1) far being json.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -