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

Ric*_*ard 6 javascript ajax jquery jsonp

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

Uncaught TypeError: Property 'photos' of object [object DOMWindow] is not a function
Run Code Online (Sandbox Code Playgroud)

查看返回的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);
 });
Run Code Online (Sandbox Code Playgroud)

谷歌搜索了一下,Uncaught TypeError: Property 'photos' of object [object DOMWindow] is not a function当jQuery尚未加载时,通常会出现错误.

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

谢谢你的建议.

Nic*_*ver 2

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

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

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
}
Run Code Online (Sandbox Code Playgroud)

或者,我认为你的意图是:

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!");
       }
   });
}
Run Code Online (Sandbox Code Playgroud)

....或者只是将两者都关闭并让 jQuerysuccess自己命名回调(默认情况下会发生这种情况,基于时间戳)。