开发者

Using AJAX with jQuery

开发者 https://www.devze.com 2023-01-25 10:14 出处:网络
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

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');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号