使用jQuery和ajax加载xml数据?

时间:2013-09-26 10:56:23

标签: jquery xml ajax

我正在尝试使用jQuery和ajax从xml文件加载som数据,但我没有从ajax请求中返回任何内容。

xml

<?xml version="1.0" encoding="utf-8" ?>
<items>
  <item key="NewSite">Create new site</item>
  <item key="EditSite">Edit site</item>
  <item key="DeleteSite">Delete site</item>
  <item key="ViewSite">View site</item>
  <item key="ViewSiteList">View full site list</item>
</items>

jQuery

var createsite = "";

//--- get trasnlated text for the notify box
$.ajax({
    url: "/Areas/Admin/Content/Scripts/admin/da-DK.xml",
    method: "GET",
    dataType: "xml",
    success: function (xml) {
        var xmlDoc = $.parseXML(xml),
        $xml = $(xmlDoc);

        $xml.find('item').each(function () {
            createsite = $(this).attr("CreateSite").text();
        });

        console.log(createsite);
    }
});

但控制台日志为空。我在这里缺少什么?

/马丁

1 个答案:

答案 0 :(得分:1)

您的代码中有错误, $(this).attr(“CreateSite”) 可以为null,因此 $(this) .attr(“CreateSite”)。text() 会抛出异常。以下是更正后的代码:

 var createsite = "";

    //--- get trasnlated text for the notify box
    $.ajax({
        url: "/Areas/Admin/Content/Scripts/admin/da-DK.xml",
        method: "GET",
        dataType: "xml",
        success: function (xml) {
            var xmlDoc = $.parseXML(xml),
            $xml = $(xmlDoc);

            $xml.find('item').each(function () {
               if($(this).attr("CreateSite")){
                  createsite=  $(this).text();
                }
            });

            console.log("createsite=>"+createsite);
        },
        error: function () {
            console.log("call failled");
        }
    });