我的 jQuery 中的变量范围问题
从后端 PHP 脚本将变量作为二维 JSON 数组检索后,我遇到了变量范围的问题。这是我的代码:
var qns, qis, ncs, nzs, tps;
function get_questions() {
var url = "php/pytania.php";
$.ajax({
cache: false,
type: "GET",
dataType: "text",
url: url,
success: function(response) {
data = jQuery.parseJSON(response);
qns = data.qns;
qis = data.qis;
ncs = data.ncs;
nzs = data.nzs;
tps = data.tps;
}
});
}
$(document).ready(function() {
var index = 0;
get_questions();
$("#question_no").text(qns[index]);
});
当我最后尝试引用我的 qns 数组时,它显示变量未定义错误。然而它在 ajax 语句中工作 - 没有问题...
谢谢,保重! :)
彼得。
I am having a problem with the scope of my variables after having retrieved them from a back-end PHP script as a 2-dimensional JSON array. Here is my code:
var qns, qis, ncs, nzs, tps;
function get_questions() {
var url = "php/pytania.php";
$.ajax({
cache: false,
type: "GET",
dataType: "text",
url: url,
success: function(response) {
data = jQuery.parseJSON(response);
qns = data.qns;
qis = data.qis;
ncs = data.ncs;
nzs = data.nzs;
tps = data.tps;
}
});
}
$(document).ready(function() {
var index = 0;
get_questions();
$("#question_no").text(qns[index]);
});
When I try to reference my qns array in the end, it displays a variable undefined error. It works however within the ajax statement - no problems there...
Thanks and take care! :)
Piotr.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是 success 方法被异步调用 - 这意味着在调用 $().ajax 并尝试引用该变量后,它尚未被分配,因为 success 回调方法尚未执行。
这可以通过将 async 选项设置为 false 来解决,如下所示:
这意味着 ajax 调用之后不会执行任何其他操作,直到您收到响应。另一种方法是将代码放置在成功回调方法本身中需要使用数组的位置。
The problem is the success method is being called asynchronously - meaning after you have called $().ajax and you try and reference the variable, it has not been assigned yet as the success callback methods hasn't been executed.
This can be solved by setting the async option to false like so:
This means that nothing else after the ajax call will be executed until you get your response. The alternative to this is placing the code where you need to use the array IN the success callback method itself.
您的问题是您试图在数据到达之前使用它。
您可以添加一个回调函数,在数据来自服务器后调用:
注意:您可以使用
dataType: "json"
,然后响应将被自动解析,并且您不需要使用parseJSON
。Your problem is that you are trying to use the data before it has arrived.
You can add a callback function that you call after the data has come from the server:
Note: You can use
dataType: "json"
, then the response will be parsed automatically, and you don't have to useparseJSON
.您应该在 ajax 请求中添加回调函数,并尝试 "$( "#question_no" ).text( qns[ index ] );"在回调函数中。您尝试在 ajax 请求实际加载变量之前访问该变量。
You should add a callback function to your ajax request, and try "$( "#question_no" ).text( qns[ index ] );" within the callback function.You try to access the variable before it was actually loaded by the ajax request.