使用 JavaScript 下载 xml 文件并将其保存在变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10721316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:49:18  来源:igfitidea点击:

Downloading an xml file with JavaScript and save it in a variable

javascriptjqueryjquery-mobilecordova

提问by Alexander

I am creating a PhoneGap Application using jQuery Mobile. I have an xml file located on a server on the internet (accessible via a web server (e.g. http://www.example.com/myXmlFile.xml)). I want to somehow read this xml file and save the content of the file in a variable as a string in Java Script. How would you do this?

我正在使用 jQuery Mobile 创建 PhoneGap 应用程序。我在 Internet 上的服务器上有一个 xml 文件(可通过网络服务器访问(例如http://www.example.com/myXmlFile.xml))。我想以某种方式读取这个 xml 文件并将文件的内容作为 Java Script 中的字符串保存在一个变量中。你会怎么做?

var contentOfXmlFile = "";

read Xml file --> Save it in the contentOfXmlFile variable.

alert(contentOfXmlFile);

After this the text from the xml file would be shown in the alert window.

此后,来自 xml 文件的文本将显示在警报窗口中。

回答by Simon MacDonald

Just use AJAX:

只需使用 AJAX:

var myXML = ""
var request = new XMLHttpRequest();
request.open("GET", "http://www.example.com/myXmlFile.xml", true);
request.onreadystatechange = function(){
    if (request.readyState == 4) {
        if (request.status == 200 || request.status == 0) {
            myXML = request.responseXML;
        }
    }
}
request.send();

The variable myXML will be an XML Document that you can manipulate.

变量 myXML 将是您可以操作的 XML 文档。

回答by RP-

You can do that with an ajax query something like follwing...

您可以使用类似以下内容的 ajax 查询来做到这一点...

jQuery.ajax({
    type :"GET",
    url : dataUrl,
    success : function(dataXML){
        //dataXML will have the complete xml..
    },
    error : function(){
        //error handler..
    }
});

Where dataUrl is your URL to xml.

其中 dataUrl 是您指向 xml 的 URL。