我经常使用 jQuery post 请求。我知道当您在响应中工作时,变量有自己的范围。有没有一种好方法可以在响应中设置变量,但可以在帖子之外使用这些变量?就像 JS 中的其他函数一样。
这是我正在做的事情的示例:
$.post('URL', { }, function(data) {
var cData = $.parseJSON(data);
$.each(cData, function(k, v) {
var cID = v.id;
});
所以我做了什么,我无法在发布请求之外访问 cID。有办法让它工作吗?
任何帮助都会很棒。 谢谢
更新:
这是我刚刚测试的示例:
var savedCount;
$.post('/app/actions/countsAction.php', { call: "getCountFullByID", countID: countID}, function(data) {
savedCount = 1;
alert(savedCount);
});
alert(savedCount);
当我运行此命令时,我收到 2 个警报。当 $.post 中触发警报时,第一个值为 1,第二个值为未定义。
最佳答案
只需在 $.post
调用之外声明变量即可:
var cID;
$.post('URL', function(data) {
var cData = $.parseJSON(data);
$.each(cData, function(k, v) {
cID = v.id;
});
});
...但不确定您想用它做什么,因为您正在循环遍历集合并不断(重新)设置单个变量的值。如果您需要跟踪所有变量,请考虑将值保存在(可能)数组中。
编辑
如果您需要执行同步(“阻塞”)$.post
调用,则可以。来自 the docs对于asynch
函数参数:
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
干杯
关于javascript - 响应 jQuery post 请求而设置的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13770150/