如何从ajax访问ajax变量

时间:2016-03-15 08:45:40

标签: jquery ajax

$(document).ready(function() {

            var items;

             $.ajax({
                url: 'item/getProducts',
                dataType: 'json',
                success: function(data){
                items=data;
                console.log(data); //this code work and show the data
                }
            });
    console.log(items);// display undefined 

});

我正在尝试访问ajax块外的变量项。但是当我控制它时它显示未定义 我怎样才能访问items变量?

3 个答案:

答案 0 :(得分:3)

您的通话$.ajax()是异步的,您无法在通话后直接访问结果。

这就是你应该使用回调函数的原因。你想要实现什么目标?

一种解决方案可以是使用带async:false参数的ajax(不推荐)。

$(document).ready(function() {
        var items;

         $.ajax({
            url: 'item/getProducts',
            dataType: 'json',
            async : false,
            success: function(data){
            items=data;
            console.log(data); //this code work and show the data
            }
        });

        console.log(items);// display undefined 
});

答案 1 :(得分:2)

创建一个JS function,它将变量items作为参数&写下你想做的任何事情。

success callback下的Ajax调用的items=data内调用此函数,否则你必须在ajax成功回调本身内写下所有逻辑。

async:false可以为您提供您现在期望的项目变量,但是因为它变成了同步ajax请求,这可能不利于用户体验&如果通话需要很长时间,可能会给浏览器冻结的印象

e.g:

<script>
function handleJSON(jsonData){
    console.log(jsonData); //wat you needed is here.

   // whatever your logic here.
}
$(document).ready(function() {

        var items;

         $.ajax({
            url: 'item/getProducts',
            dataType: 'json',
            success: function(data){
            items=data;
            handleJSON(items); // or pass the data directly here.
            }
        });
});
</script>

答案 2 :(得分:1)

这是因为JavaScript是单线程的,而JQuery ajax()方法是异步的。

在进行AJAX调用之后,JavaScript引擎不会等待响应返回。因此JavaScript引擎将执行console.log(items);。它提供未定义,因为在执行console.log(items);时,item变量未设置为来自AJAX请求。

请注意,在从AJAX请求打印数据之前,在控制台中打印undefined

您可以通过向AJAX调用添加async : false参数来告诉JavaScript引擎等待来自服务器的响应。