微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 在ajax函数外传递变量[复制]

参见英文答案 > How do I return the response from an asynchronous call?                                    34个
请帮忙 – 我有以下代码在警报中返回变量’results’.我想在函数之外使用这个变量,并且无法获得回调或外部声明才能成功运行.我确定我是一个布偶,所以我为这个基本问题道歉…..

<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script>

$(function () {
    $.ajax({
        type: 'POST',
        dataType: 'jsonp',
        url: 'https://creator.zoho.com/api/json/my-company-culture/view/PageFeed_Report?scope=creatorapi&authtoken=d670dc68ac0f6d7ca389e7b206a25045',
        success: function (results) {
            var raw_result=JSON.stringify(results);
            alert(results);
        }
    });
});

 </script>

解决方法:

jQuery 1.5解决这个问题的方法是使用延迟对象:

var res;

var ajax = $.ajax({
    type: 'POST',
    dataType: 'jsonp',
    url: ...
}).done(function(results) {
    // you may safely use results here
    res = results;
    ...
});

// you cannot safely use 'res' here, only in code
// invoked via a 'done' callback on the `$.ajax` promise

console.log(res);    // undefined

尝试将结果复制到外部作用域中的其他变量是不正确的,除非您确保在AJAX调用完成之前没有其他代码尝试访问该变量.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐