Javascript全局变量未正确更新

Javascript全局变量未正确更新,javascript,ajax,Javascript,Ajax,我需要行是一个全局数组,但是当我使用console.log比较函数内部和外部的值时,内部的行可以正常工作,但是外部的行仍然是空的。我是不是遗漏了什么 var lines = new Array(); $.ajax({ type: "GET", url: "posts_replied_to.txt", success: function(content) { console.log("success"); lines = conten

我需要行是一个全局数组,但是当我使用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);

是的,AJAX是异步函数。所以,在外部的“console.log(lines)”命令中,在AJAX之前运行

你可以说:错


这里的问题不是关于全局变量。这就是异步性问题。在调用ajax请求外部的console.log()时,不会调用ajax成功回调。这就是您无法获得正确值的原因

async function doAjax() {
    return await $.ajax({
        type: "GET",
        url: "posts_replied_to.txt"
    });
}

let lines = await doAjax()
lines = content.split('\n')
console.log(lines)
使用以下命令尝试此代码
要获得预期的结果。

在得到响应之前,您的第二个控制台也会执行日志代码,因为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);

尝试使用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.
  });

您缺少AJAX是异步的。