Javascript全局变量未正确更新

时间:2018-02-06 07:44:19

标签: javascript ajax

我需要将行作为全局数组,但是当我使用console.log来比较函数内部和函数外部的值时,内部的一个工作正常,但外部的一个仍然是空的。我在这里错过了什么吗?

      var lines = new Array();
  $.ajax({
    type: "GET",
    url: "posts_replied_to.txt",
    success: function(content) {
      console.log("success");
      lines = content.split('\n');
      console.log(lines);
    },
    error: function() {
      console.log("error");
    }
  });
  console.log(lines);

4 个答案:

答案 0 :(得分:2)

这里的问题不是关于全局变量。它是异步性问题。在调用ajax请求之外的console.log()时,不会调用 ajax成功回调。这就是为什么你不能获得正确的值。< / p>

^(?:(?:[Ff][gG]|0[146]|[Kk][Ll][Mm])(?=.{10}$)|(?:05|[pP][Tt])(?=.{11}$))[0-9]*(?:[Ff][rR])?$
                       ^^^^^^^^^^^^

使用此代码 Async获得预期结果。

答案 1 :(得分:0)

是的,AJAX是异步函数。因此,在'console.log(lines)'命令之外,在AJAX之前运行。

您可以使用AJAX asyn:false

What does "async: false" do in jQuery.ajax()?

答案 2 :(得分:0)

在您的GET响应之前,您的第二个console.log代码也会执行,因为ajax不是异步的。改变如下,

var lines = new Array();
 $.ajax({
   type: "GET",
   url: "posts_replied_to.txt",
   async: false,
   success: function(content) {
     console.log("success");
     lines = content.split('\n');
     console.log(lines);
   },
   error: function() {
     console.log("error");
   }
 });
 console.log(lines);

答案 3 :(得分:0)

尝试使用ajax调用返回的promise对象。

var lines = new Array();
  var promise_obj  = $.ajax({
        type: "GET",
        url: "posts_replied_to.txt"
  }).promise();

  promise_obj.done(function(response)
  {
    lines = response.split('\n');
    console.log(lines);
    // Rest of your logic goes here where you want to use lines.
  });
相关问题