javascript - Ajax异步请求问题

标签 javascript jquery ajax

在下面,这段代码有效,当我使用alert()框时,我按下警报框,然后,内容被加载到页面上。但是,如果我删除alert()框,那么内容就不会被加载。只是为了让您知道谁读到了这篇文章,抱歉,我已经阅读了很多有关“Ajax”请求的内容,但是,我无法理解这一点。对此有什么帮助吗?

var myPage = myPage || {};
myPage.datas = "";
myPage.Content = (function(){
$.ajax({
async: true,
    type:'GET',
    url: 'JSON/carousel-data.json',
    dataType: "json",
    success: function(data) {
       myPage.datas = myPage.dataRetive(data); 
    }
});
})(); 

myPage.dataRetive = function(dataIn){
return dataIn;
}

alert(myPage.datas); // Here is the place, if i use this alert, then, content is loading, otherwise, it is not.

myPage.globals = {
Contact: $("#Contact")[0],
About : $("#About")[0],
Careers : $("#Careers")[0],
sampMaxLimits: 20,
Images:  {
  fpn1: myPage.datas[0].image, // error comes these place
  fpn2: myPage.datas[1].image,
  fpn3: myPage.datas[2].image
}

}

最佳答案

修改您的代码如下

$.ajax({
async: true,
type:'GET',
url: 'JSON/carousel-data.json',
dataType: "json",
success: function(data) {
   myPage.datas = myPage.dataRetive(data); 
   myPage.globals = {
        Contact: $("#Contact")[0],
       About : $("#About")[0],
        Careers : $("#Careers")[0],
     sampMaxLimits: 20,
      Images:  {
        fpn1: myPage.datas[0].image, // now myPage.datas will be available
       fpn2: myPage.datas[1].image,
      fpn3: myPage.datas[2].image
   }

  }


}
});

现在它将正确更新myPage.globals

关于javascript - Ajax异步请求问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29003334/

相关文章:

javascript - jQuery - 按钮单击不起作用

javascript - 文本区域换行jquery

php - 即使我正在工作, session 也会过期, session 生命周期,Ajax 和 Symfony2

javascript - 使用 AJAX 在 Node.js 上进行数据库查询

javascript - iMacros TAG 查找 TXT 并单击附近的(上一个)链接

javascript - 如何使用 JS/JQuery 使用文件 :///protocol and IE/Edge browser? 存储持久数据

javascript - 使用 leaflet js 将单击类添加到路径

javascript - d3 csv 读入数组中的对象

jquery - 带有垂直子菜单的全宽水平菜单,其中有一个垂直子菜单

jQuery AJAX 每个循环使用append 和html