未捕获的TypeError:属性…不是函数 – 页面加载后

我正在使用跨域Ajax请求到外部API。 每隔一段时间它就会失败,并显示控制台消息:

Uncaught TypeError: Property 'photos' of object [object DOMWindow] is not a function 

查看返回的JSON,它是有效的JSON,因此它不是外部API的错误。

我无法可靠地重现错误:似乎触发错误的唯一因素是我快速重复地调用请求。

在这种情况下,我在用户移动Google地图时调用Ajax请求(向地图添加标记),如果用户移动得太快,就会发生这种情况。

以下是我的代码的相关部分:

 // Code located inside an external JS file referenced inside the head // Not wrapped inside document.ready - but all the code setting up // the map (calling a function which calls a function which adds the // tilesloaded listener) *is* inside document.ready function addMarkers() { var pm_url = "http://www.cyclestreets.net/api/photos.json?key=" + MY_KEY; $.ajax({ url: pm_url, crossDomain: true, contentType: "application/json", dataType: 'jsonp', data: pmdata, jsonpCallback: 'photos', success: function(data) { // TBA }, error: function() { alert("Sorry, error retrieving photos!"); } }); } google.maps.event.addListener(map, 'tilesloaded', function() { addMarkers(map); }); 

谷歌搜索了一下,错误Uncaught TypeError: Property 'photos' of object [object DOMWindow] is not a function通常似乎在没有加载jQuery时发生。

但是,我没有看到这在这里是相关的,因为函数是从map的tilesloaded事件调用的 – 它通常不会在第一次触发时,它会在五或六个快速地图resize后触发。 所以,如果它工作一次,页面肯定不会’忘记’jQuery?

谢谢你的建议。

如果要指定jQuery从success处理程序创建的函数的名称 ,但实际上没有定义要使用的单独函数 , 则应使用jsonp: 'photos'而不是jsonpCallback: photos 。 目前它正在使用URL中的photos ,这意味着当JSONP响应返回时,它正在调用photos({ ...data... }) ,而这不存在。 在$.ajax()上使用jsonp选项会创建它。 你有几个选择。

您可以通过以下两种方式执行此操作(在全局范围内):

 function addMarkers() { var pm_url = "http://www.cyclestreets.net/api/photos.json?key=" + MY_KEY; $.ajax({ url: pm_url, crossDomain: true, contentType: "application/json", dataType: 'jsonp', data: pmdata, jsonpCallback: 'photos', error: function() { alert("Sorry, error retrieving photos!"); } }); } function photos(data) { // TBA } 

或者,我想你想要的是什么:

 function addMarkers() { var pm_url = "http://www.cyclestreets.net/api/photos.json?key=" + MY_KEY; $.ajax({ url: pm_url, crossDomain: true, contentType: "application/json", dataType: 'jsonp', data: pmdata, jsonp: 'photos', success: function(data) { // TBA }, error: function() { alert("Sorry, error retrieving photos!"); } }); } 

….或者只是将两者都关闭并让jQuery命名success回调本身(默认情况下,这基于时间戳)。