我遇到一种情况,我想拥有一个全局变量,例如它将从某个服务器的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
}
我尝试过的方法如下:
需要注意的是,在完成页面加载时以及在ajax调用之后,正在从HTML按钮调用something()函数。因此价值已经可用。
答案 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");
});
});