如何在JavaScript中加载XML?

时间:2015-12-18 16:38:20

标签: javascript xml

我有以下代码,我想调用XML文件,但收到以下错误GET http://tdhdemo.com/generator/data/xml/ 403 (Forbidden)

任何人都可以向我解释我错在哪里,因为我真的无法弄明白吗?

这是我正在使用的代码:

var dataPath = "data/";
var xmlPath = "data/xml/";
var canvasObject = '';
var canvas = {
        width: 0,
        height: 0
    };
var data = {
        width: 0,
        height: 0,
        date: 0,
        place: 0,
        city: 0,
        country: "ro",
        countries: {}
    };
function startUp(){
        canvasObject = document.getElementById("generatorCanvas");
        resetCanvas();
        loadCountries();
        formEvents();
    }
function loadCountries(){
        $.get(dataPath+'countries.json', function(data) {
            data.countries = data;
            addCountriesToSelect();
        });
    }
function addCountriesToSelect(){
        $.each(data.countries, function(index, val) {
             $('[name=country]').append('<option value="'+index+'">'+val.name+'</option>');
        });
    }
function resetCanvas(){
        makeLogo();

        width = data.width;
        height = $("#generatorLogo").height() / 100 * 65;

        canvasObject.width = width;
        canvasObject.height = height;
        canvasContext = canvasObject.getContext("2d");

        canvasContext.fillStyle = "#cd2026";
        canvasContext.fillRect(0,0,width,height);

        canvasContext.font="20px HMAmpersand";
    }

2 个答案:

答案 0 :(得分:0)

检查xml端点。这里有一些数据操作代码,但只需从服务器读取XML就可以使用此代码完成(使用jQuery)

 $(document).ready(function(){
  $.ajax({
   type: "GET",
   url: "data.xml",
   dataType: "xml",
   success: function(xmlData) {
    //manipulate XML data here

   }
 });
});

答案 1 :(得分:-1)

您可以从w3schools

加载此代码中的javascript
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
        myFunction(xhttp);
        }
    };
    xhttp.open("GET", "books.xml", true);
    xhttp.send();
function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    document.getElementById("demo").innerHTML =
    xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
}