javascript - 响应 jQuery post 请求而设置的变量

标签 javascript jquery

我经常使用 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/

相关文章:

javascript - 单击后退按钮时加载微调器和显示消息

php - 如何使用 <map> 与鼠标悬停自动链接到另一个页面

jquery - 使用 Angular + JQuery 实现动态 Pinterest 风格的布局

javascript - 单击页面中的其他位置时将搜索恢复到其原始宽度?

php - 在 PHP 中使用电子邮件和密码注册后无法登录

javascript - 从 Iframe 加载父窗口中的页面

javascript - 使用 jquery 的输入框中的值总和不起作用

javascript - xcode 5,我想删除 uiWebView 中的一个类

javascript - jQuery children 返回一个 bool 值?

jquery - 使用 jquery sortable 时如何复制项目?