[英]jquery.post and variable scope
I'm new to javascript and have the following problem. 我是javascript新手,有以下问题。 I want to load some json from an api.php and succeed with the returned value to fill my GUI.
我想从api.php加载一些json,然后使用返回值成功填充我的GUI。
$( '#data_button' ).click(function() {
$.post( 'api.php', function( data ) { json = data; });
$('#data1').empty().append( json[0].name + ' | ' + json[1].name );
});
So I wanna click a button, then it fetches via post some data ans save this to the variable data. 所以我想单击一个按钮,然后通过发布获取一些数据并将其保存到变量数据中。 As it should be an object (json object?) I thought I just can use it as above... But that doesn't work.
因为它应该是一个对象(json对象?),所以我认为我可以像上面一样使用它...但这是行不通的。 Console say: can't find variable json.
控制台说:找不到变量json。
Any hints? 有什么提示吗?
You have your appending outside the post callback function. 您可以在post回调函数之外进行追加。 Try this:
尝试这个:
$( '#data_button' ).click(function() {
$.post( 'api.php', function( data ) {
json = data;
$('#data1').empty().append( json[0].name + ' | ' + json[1].name );
});
});
jquery post as default works asynchronously which means that the line: jQuery post作为默认异步工作,这意味着该行:
$('#data1').empty().append( json[0].name + ' | ' + json[1].name );
occur before the post request have returned the data. 在发布请求返回数据之前发生。
this how it should be done: 这应该怎么做:
$( '#data_button' ).click(function() {
$.post( 'api.php', function( data ) {
$('#data1').empty().append( data[0].name + ' | ' + data[1].name );
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.