本文介绍了Google Places API jQuery.ajax()请求因工作URL失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将以下URL粘贴在浏览器标签中:

If I paste the following URL in a browser tab:

https://maps.googleapis.com/maps/api/place/search/json?location=51.5237587%2C-0.1583642&radius=500&types=bar&key=MY_KEY_HERE&sensor=false

...我从Google Places API获得了预期的JSON响应(当然,在这里和下面的.ajax()中,MY_KEY_HERE替换为实际的密钥).但是,当使用此jQuery.ajax()构造时:

... I get the expected JSON response from the Google Places API (MY_KEY_HERE is of course replaced with the actual key, here and in the .ajax() below). However when using this jQuery.ajax() construct:

$.ajax({
     type: 'GET',
     url: "https://maps.googleapis.com/maps/api/place/search/json",
     data: {"location" : latlng, "radius" : 500, "types" : "bar", "key" : "MY_KEY_HERE", "sensor" : "false",},
     dataType: "json",
     success: function(data)
     {
       var pubResults = data;
     },
     error: function(data)
     {
       alert(JSON.stringify(data));
     },
     complete: function(data)
     {
       initialize($.oneapi.latitude, $.oneapi.longitude, pubResults);
     }
   });

...然后未达到成功块,而是输出 error 块:

...then the success block is not reached, instead the error block outputs:

{"readyState":0,"responseText":"","status":0,"statusText":"error"}

在Firefox 5.01中进行测试. Web控制台确认.ajax()正在获取此问题顶部提到的URL.知道为什么jQuery调用该URL会导致错误,但是将相同的URL粘贴到浏览器选项卡中会导致预期的JSON吗?

Testing in Firefox 5.01. The Web console confirms that .ajax() is GETting the URL mentioned at the top of this question. Any ideas why the jQuery call to that URL would result in the error, but the same URL pasted into a browser tab results in the expected JSON?

非常感谢您的光临!

推荐答案

这是跨域请求.默认情况下,浏览器会阻止跨域网站的响应.您需要使用jsonp作为数据类型.就像google一样,您可以看到如何使用jquery API来完成.堆栈溢出也有关于这些的问题.

This is a cross domain request. Browsers by default block responses from cross domain sites. You need to use jsonp as the datatyoe. Just google the same and you can see how it can be done using the jquery API. Stack overflow has questions around these too.

在相同的原始策略下,从server1.example.com服务的网页通常无法连接到server1.example.com以外的服务器或与之通信. HTML元素是一个例外.利用元素的开放策略,某些页面使用它们来检索Javascript代码,该Javascript代码对来自其他来源的动态生成的JSON格式的数据进行操作.这种使用模式称为JSONP.

Under the same origin policy, a web page served from server1.example.com cannot normally connect to or communicate with a server other than server1.example.com. An exception is the HTML element. Taking advantage of the open policy for elements, some pages use them to retrieve Javascript code that operates on dynamically-generated JSON-formatted data from other origins. This usage pattern is known as JSONP.

这篇关于Google Places API jQuery.ajax()请求因工作URL失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 09:50