[英]Get JSON via javascript [Cross-Domain]
Please help me with the following situation: 请在以下情况下帮助我:
there is the page p1.aspx with only one button: 页面p1.aspx只有一个按钮:
<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. 上面是我想通过javascript获取JSON文本的方式。
Web application http://localhost/p2.aspx
is redirected to http://localhost/p3.aspx
inside. Web应用程序
http://localhost/p2.aspx
重定向到内部的http://localhost/p3.aspx
。 And the page http://localhost/p3.aspx
again is redirected back to http://localhost/p2.aspx?code=1
. 然后页面
http://localhost/p3.aspx
再次重定向回http://localhost/p2.aspx?code=1
。
code=1
is the value I want read in my javascript code. 是我想在我的JavaScript代码中读取的值。 But it's not works.
但这是行不通的。
In p2.aspx I generate JSON data as following 在p2.aspx中,我生成如下的JSON数据
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonString);
Response.End();
After this I can not read json data via javascript. 之后,我无法通过javascript读取json数据。 But if I just put the
http://localhost/p2.aspx
via web browser then it get json data on the page. 但是,如果我只是通过网络浏览器放置
http://localhost/p2.aspx
,则它会在页面上获取json数据。
You need to use JSONP
if you want that to work. 如果您想使用
JSONP
则需要使用它。
So your script should take into account the callback
parameter: 因此,您的脚本应考虑
callback
参数:
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 ?
注意
callback
查询字符串参数如何设置为?
. 。 Basically jQuery will translate this to a request that looks like this:
基本上,jQuery会将其转换为如下所示的请求:
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: 并且您的服务器端脚本当然应该返回
JSONP
,这是包装在回调名称中的JSON
字符串:
jQuery123456789....({"code":1})
Also make sure that the jsonString
variable used in your code is an actual JSON string (as its name suggests). 还要确保代码中使用的
jsonString
变量是实际的JSON字符串(顾名思义)。 Because what you have shown in your question ( code=1
) is very far from being JSON. 因为您在问题(
code=1
)中显示的内容与JSON相距甚远。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.