1

我有以下代码。

var dat = null;

$.get("example.com", function(data){
    dat = data;
    alert(dat); // Has the info.
});

alert(dat); // null.

我如何访问dat外部$.get

4

2 回答 2

2

访问该变量应该可以正常工作。问题是设置 dat 的函数将在最后一个警报之后运行。

该函数是一个回调。它仅在 get 完成后运行,而最后一个警报将立即运行。

这是回调后链接代码的一种方法

var dat = null;

$.get("example.com", function(data){
    dat = data;
    alert(dat); // Has the info.
}).then(function() {
   alert(dat); // Has the info too.
});
于 2013-06-24T03:02:17.517 回答
0

线路警报(数据);在 $.get() 之前执行,因为异步。将 $.ajax() 与 async:false 一起使用,或者将 alert(data) 放入成功的 $.get() 中:

$.ajax({
    type: "GET",
    async: false,
    url: "example.com",
    success: function(data) {
           dat = data;
           alert(dat);
    },
    error: function(e) {
        console.log(e); //error
    }
});
于 2013-06-24T03:08:23.523 回答