jQuery加载文本文件数据 [英] jQuery to load text file data

查看:106
本文介绍了jQuery加载文本文件数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用外部脚本文件中的$ .get()函数从我的服务器上的文本文件加载数据。我的代码如下:

I'm trying to load data from a text file on my server using the $.get() function in an external script file. My code is as follows:

  /* 
   * Load sample date
   */
  var stringData;
  $.get("http://localhost/webpath/graphing/sample_data.txt", function(data){
      stringData = data;
      //alert("Data Loaded: " + stringData);
      });
  //Split values of string data
  var stringArray = stringData.split(",");
  alert("Data Loaded: " + stringData);

当我在$ .get()函数内部时,我可以看到stringData var get peopulated就好了并且对警报的调用确认它包含来自示例文本文件的数据。但是,当我离开$ .get()函数时,stringData var不再显示。我不太了解该函数如何工作以了解它为什么没有像我预期的那样做。我想要它做的就是将文本数据加载到变量中,以便我可以使用它。感谢任何帮助。

When I'm inside the $.get() function I can see stringData var get peopulated just fine and the call to alert confirms that it contains data from the sample text file. However, when I get outside the $.get() function, the stringData var no longer shows. I don't know enough about how the function works to know why it is not doing as I expected. All I want it to do is load the text data into a variable so I can work with it. Any help is appreciated.

推荐答案

get是异步的意思是它调用服务器并继续执行其余的代码。这就是你有回调方法的原因。无论您打算如何处理返回数据,都应该在回调方法(放置警报)中进行。

get is asynchronous meaning it makes a call to the server and continues executing the rest of the code. This is why you have callback methods. Whatever you intend to do with the return data do it inside the callback method(where you have put the alert).

get,post都是异步的。您可以使用

get, post are all asynchronous. You can make a synchronous call by using


  1. 进行同步通话.ajaxSetuprel =noreferrer> $。ajaxSetup({async:false}); 代码中的任何位置。这会影响代码中的所有ajax调用,所以要小心。

  1. using $.ajaxSetup({ async: false }); anywhere in your code. This will affect all ajax calls in your code, so be careful.

$。ajax async:false 例如如下所示。

请查看上面提到的代码和API文档链接以解决您的问题。

Look at the below code and the API docs link mentioned above to fix your problem.

  /* 
   * Load sample date
   */
  var stringData = $.ajax({
                    url: "http://localhost/webpath/graphing/sample_data.txt",
                    async: false
                 }).responseText;

  //Split values of string data
  var stringArray = stringData.split(",");
  alert("Data Loaded: " + stringData);

这篇关于jQuery加载文本文件数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆