2012-09-29 75 views
2

关闭jQuery中的异步请求解决了问题。jQuery AJAX请求在页面加载时不起作用,但它可以在调试控制台中工作

我在我的网页(使用jQuery)以下JavaScript & AJAX请求:

"use strict"; 

    var hsArea, counter, hotspots, count; 
    counter = 4; 
    count = 0; 
    hotspots = {}; 

    function fetchHotspotList() { 
     $.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) { 
      hotspots = json; 
     }); 
    } 

    function displayHotspot(type, id, number) { 
     $.ajax({ 
      url: '/alpha/engine/hotspots/gethotspot.php', 
      dataType: 'json', 
      data: {'type' : type, 'id' : id}, 
      success: function(json) { 
       console.log(json); 
       var hotspot, extract; 
        extract = json.content; 
        extract = extract.replace(/<(?:.|\n)*?>/gm, ''); 
        extract = extract.substring(0, 97); 
        extract = extract + "..."; 
        json.content = extract; 

        hotspot = document.createElement("div"); 
        hsArea.append(hotspot); 
        hotspot.setAttribute('class','hotspot'); 
        hotspot.setAttribute('id','hotspot' + number); 

        $(hotspot).css('position', 'absolute'); 
        $(hotspot).css('top', number * 100 + 100); 
        $(hotspot).css('left', number * 100 + 110); 

        hotspot.innerHTML = "<h1>"+ json.title + "</h1><p>" + json.content + "</p>"; 
      }, 
      error: function(XMLHttpRequest, textStatus, errorThrown) { 
       alert(textStatus, errorThrown); 
      } 
     }); 
     } 

     function listHotspots() { 
      for(count = 0; count < counter; count++) { 
       (function(count) { 
        displayHotspot('scribble',hotspots[count], count); 
        count = count + 1; 
       })(count); 
      } 
     } 

     function loadHotspots() { 
      fetchHotspotList(); 
      listHotspots(); 
     } 

    $(document).ready(function() { 
     hsArea = $("#hotspotArea"); 
     fetchHotspotList(); 
     listHotspots(); 
    }); 

(对不起!格式化是有点过了) - 现在,$(文件)。就绪()功能分配hsArea变量,因为它应该,但是,fetchHotspotList()和listHotspots()的组合返回:

Uncaught TypeError: Cannot call method 'replace' of null

但是,如果谷歌浏览器的Javascript控制台,我跑:

loadHotspots();

它将从AJAX请求的数据,并正确地显示在页面上。起初我以为问题是我没有使用$(document).ready()处理程序,但添加它并没有解决它。在body标签内部都没有使用onload处理程序。

任何帮助将不胜感激。

Regards, Ben。

+0

只是为了澄清,这是所有包装在标签! – BnMcG

+0

您正在'extract'上调用'replace',并从'json.content'获取'extract'。如果返回的'json'数据存在索引'content' – air4x

回答

1

这可能是由于您的listHotSpots函数在fetchHotSpots返回之前调用(因为它是异步调用)。

你最好链的listHotSpots执行到的fetchHotSpots完成,像这样:

function fetchHotspotList() { 
    $.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) { 
     hotspots = json; 
     listHotSpots(); 
    }); 
} 

你可能会更好修改listHotSpots采取JSON数据从你的AJAX调用返回。希望这可以帮助!

+0

感谢您的帮助David,但是,我已经完全关闭了异步调用,这解决了问题,但是我也会尝试您的方法! 编辑 - 刚测试过:这种方法也可以! – BnMcG

相关问题