jQuery AJAX的JavaScript作用域

时间:2018-12-19 06:22:54

标签: javascript jquery html

我遇到一种情况,我想拥有一个全局变量,例如它将从某个服务器的jQuery Ajax中获取其值,然后希望该值在其他函数调用时可用。可视化:

var a = [];

$(document).ready(function () {
  $.ajax({
    type: 'GET',
    url: 'some url',
    success: function (response) {
      a = response.somearray;
    },
    error: function () {
      alert("Not successfull");
    }
  });
});

function something() { // this function will be called onclick of a button in html
  console.log(a); // here I want the value that came from the server. But currently, it's printing empty array
}

我尝试过的方法如下:

  1. 从(a)中删除var关键字以使其具有全局性。
  2. 没有为上面的(a)声明分配任何值(这里为空数组)(尽管那是一个错误的错误)。
  3. 完全从顶部删除(a)声明。

需要注意的是,在完成页面加载时以及在ajax调用之后,正在从HTML按钮调用something()函数。因此价值已经可用。

2 个答案:

答案 0 :(得分:1)

这是您想要的工作示例,请检查控制台日志: https://codepen.io/antoniandre/pen/NebpQj?editors=0010

var a = [];

$(document).ready(function () {
  $.getJSON("https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
    tags: "snowboarding",
    tagmode: "any",
    format: "json"
  })
  .done(function (response) {
    a = response.items;
    // something(); Don't need this.
  });
});

function something() { // this function will be called onclick of a button in html
  console.log(a); // here I want the value that came from the server. But currently, it's printing empty array
}

编辑:

HTML:

<button onclick="something()">hello</button>

答案 1 :(得分:-1)

范围丢失了,因为ajax回调是异步函数。我认为应该是

var a = [];

$(document).ready(function () {
  var me = this;
  $.ajax({
    type: 'GET',
    url: 'some url',
    success: function (response) {
      me.a = response.somearray;
    },
    error: function () {
      alert("Not successfull");
    });
});