访问 xmlHTTP 请求函数范围之外的 JSON 对象

时间:2021-02-23 14:07:26

标签: json xmlhttprequest

我有一个 .json 文件,我同时使用 xmlHTTP 请求访问该文件。

<script>

  var act_obj_array;

  // Get file activities.json and create JSON object
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if ( this.readyState == 4 && this.status == 200 ) {
      act_obj_array = JSON.parse( this.responseText);
    }
    console.log(this.responseText);
    console.log('Inside function = ' + act_obj_array);
  };

  xmlhttp.open( "GET", "activities.json", true);
  xmlhttp.send();

  console.log( 'Outside function = ' + act_obj_array);

</script>

我需要访问 JSON 对象 act_obj_array,最好在函数中,稍后在我的脚本中。问题是,act_obj_array 只能在 xmlHTTP 请求中的函数范围内访问。我不想每次需要访问我的 JSON 对象时都必须继续使用 xmlHTTP 请求。换句话说,我希望 act_obj_array 是一个全局变量,可以在我的脚本中的任何地方访问。

0 个答案:

没有答案