I have a problem with this code. This happens: just launch the code from console.log I get null, if I press the update button function works.
我有这个代码的问题。发生这种情况:只是从console.log启动代码我得到null,如果我按下更新按钮功能工作。
why is this happening? how do I fix?
为什么会这样?我该如何解决?
var urljson = "data_json.php";
var data = null;
var jqXHR = $.ajax
({
type: "GET",
url: urljson,
dataType: 'json',
success: successHandler
});
function successHandler(result) {
data = result;
}
function update(){
var jqXHR = $.ajax
({
type: "GET",
url: urljson,
dataType: 'json',
success: successHandler
});
function successHandler(result) {
data = result;
}
}
$(document).ready(function(){
console.log(data) //// null
});
document.getElementById('update').addEventListener('click', function() {
update();
console.log(data) //// Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, other 3213… ]
});
2 个解决方案
#1
1
$.ajax()
returns results asynchronously. Use success
handler or .then()
chained to $.ajax()
to process response returned from request.
$ .ajax()以异步方式返回结果。使用成功处理程序或.then()链接到$ .ajax()来处理从请求返回的响应。
function update() {
var jqXHR = $.ajax({
type: "GET",
url: urljson,
dataType: "json",
success: successHandler
});
function successHandler(result) {
data = result;
// do stuff with `data` here
console.log(data);
}
}
$(document).ready(update);
jsfiddle https://jsfiddle.net/89jkzzyk/
#2
0
When the page loads, update()
is not getting called, thus data
is null. Add your function call to $(document).ready()
and it should work.
页面加载时,不会调用update(),因此数据为空。将函数调用添加到$(document).ready(),它应该可以工作。
#1
1
$.ajax()
returns results asynchronously. Use success
handler or .then()
chained to $.ajax()
to process response returned from request.
$ .ajax()以异步方式返回结果。使用成功处理程序或.then()链接到$ .ajax()来处理从请求返回的响应。
function update() {
var jqXHR = $.ajax({
type: "GET",
url: urljson,
dataType: "json",
success: successHandler
});
function successHandler(result) {
data = result;
// do stuff with `data` here
console.log(data);
}
}
$(document).ready(update);
jsfiddle https://jsfiddle.net/89jkzzyk/
#2
0
When the page loads, update()
is not getting called, thus data
is null. Add your function call to $(document).ready()
and it should work.
页面加载时,不会调用update(),因此数据为空。将函数调用添加到$(document).ready(),它应该可以工作。