jQuery to load text file data
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);
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 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 are all asynchronous. You can make a synchronous call by using
using
$.ajaxSetup({ async: false });
anywhere in your code. This will affect all ajax calls in your code, so be careful.$.ajax
withasync: false
e.g. shown below.
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);
The $.get function is asynchronous. You'll need to do any work on the returned data in the callback function. You can move that function to not be inline to clean up the code as well.
function parseData(data){
//do something with the data
alert("data is: " + data);
}
$.get("http://localhost/webpath/graphing/sample_data.txt",parseData);
精彩评论