为什么这个 JQuery Ajax 调用不起作用?
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript" language="javascript">
$.ajax({
type: "GET",
cache: false,
url: 'http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=school',
contentType: "application/json; charset=utf-8",
success: function(msg) {
alert(""+msg.length);
},
error: function (e) {
alert("Failed to Get declassification details");
}});
</script>
</body>
</html>
我无法弄清楚这个 AJAX 调用出了什么问题。WENT 通过了这个论坛上的几个 SIMILAR
问题,但没有一个对我有用。
我必须从 Google 搜索中获取 JSON 格式的结果集。
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript" language="javascript">
$.ajax({
type: "GET",
cache: false,
url: 'http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=school',
contentType: "application/json; charset=utf-8",
success: function(msg) {
alert(""+msg.length);
},
error: function (e) {
alert("Failed to Get declassification details");
}});
</script>
</body>
</html>
I am not able to figure out whats going wrong with this AJAX call.WENT Through several SIMILAR
question on this forum, but none was working for me.
I have to Get the resultset from Google search in JSON format.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于跨域安全策略,浏览器正在丢弃请求。
尝试使用 JSONP(数据类型:“jsonp”)。
由于安全限制,通常无法向第三方网站发出 Ajax 请求。但有多种客户端技术可以解决此限制,其中之一就是 JSONP。
您无法从 JSONP 获得的一件事是网络错误通知或任何对格式错误的响应做出良好响应的通知,因此您必须接受这一点,作为与调用其他域上的服务的能力之间的权衡。
JSONP 工作的原因和方式:
查看响应中的差异:
http://ajax.googleapis.com/ajax/ services/search/local?v=1.0&q=school
与
http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=school&callback=jquery_created_function
The browser is dropping the request because of cross domain security policy.
Try using JSONP (dataType: "jsonp").
Ajax requests to third party websites are normally not possible because of security restrictions. But there are several client-side techniques to work around this restrictions and one of them is JSONP.
One thing you will not get from JSONP is notification of network errors or anything that responds nicely to badly formed responses, so you have to accept that as a tradeoff with the ability to invoke services on other domains.
Why and how JSONP works:
See the difference in the response:
http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=school
vs
http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=school&callback=jquery_created_function
您应该使用
dataType
而不是“contentType”。这是代码:这是工作示例。
来自文档:
You should use
dataType
instead of 'contentType'. Here is code:Here is working example.
From documentation: