How could I GET
the information in an XML file and read it into an array on an object so that I'd be able to access it from any function? What's the best way to go about this? I'm using jQuery and AJAX.
Thanks, Elliot Bonneville
EDIT: Here's some example code of what I have so far:
function GetQuestions() {
$.ajax({
type: "GET",
url: "questions.xml",
dataType: "xml",
success: function(xml) {
x = 0;
x = $(xml).find('Questions').length;
var questionID = $.random(x);
//Her开发者_运维问答e's where I need to iterate through the questions to find the one with the ID specified by the random var above.
}
}
}
You could use $.get:
$.get('content/file.xml', function(data) {
// convert to JSON for easier manipulation
}, "xml");
As you want to "access it from any function", you'd probably need to convert the XML to JSON.
There is no built-in functionality to do this - you'd need a plugin like the one here.
Which also begs the question - why not just return JSON from the server in the first place?
This is as of jquery xml reader .. You need to read node by node and insert to array, then to serialize an array to json format with serializeArray jquery function, I didn't check the code , but this is probably what you need.
$(document).ready(function(){
var mystuff = new Array();
$.ajax({
type: "GET",
url: "sites.xml",
dataType: "xml",
success: function(xml) {
mystuff = $(xml).find('site');
}
});
var serialized = mystuff.serializeArray()
});
$.get('/path/to/file.xml', function(data){
alert('xml loaded.');
}, 'xml');
精彩评论