我正在使用 ajax 从数据库中检索数据并将其存储为数组,然后返回结果。我的目标是,当用户单击“单击我”按钮时。我想从返回的数据中提醒第一个数组。但是,我下面的代码没有返回任何内容。
<input type="button" id="click_me" value="Click Me"/>
var data_array;
$.post('generate.php', {id: id}, function(data){
data_array= data;
});
$('#click_me').click(function(){
alert(data_array[0]);
});
生成.php
<?php
header('Content-Type: application/json');
$array = array('Hello', 'Good Morning', 'Nice to meet you');
echo json_encode($array);
?>
最佳答案
不要将数据数组声明为局部变量,通过在嵌套成功回调声明中删除“var”来使用全局变量:
$.post('generate.php', {id: id}, function(data){
data_array= data;
});
关于php - 我如何使用从 Ajax 返回的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16886256/