使用jQuery

时间:2016-02-23 14:32:17

标签: javascript jquery xml

我已经浏览了stackoverflow一段时间并且没有找到适合我的问题的答案 - 我想在单击按钮时加载我的xml文件的某个部分。我想将我的xml文件的一部分加载到'内容' DIV。

这是我的HTML代码:

<div>
  <input type="button" id="click"/>
  <div id="content">

  </div>
</div>

这是我的XML:

<?xml version="1.0" encoding="utf-8"?>
<books>
    <book id="jeff">
    <author>Jeffrey </author>
    <title>Books 1</title>
</book>
<book id="jerry">
    <author>Jerry</author>
    <title>Books 2</title>
</book>
<book id="jimmy">
    <author>Jimmy</author>
    <title>Boks 3</title>
</book>
<book id="jem">
    <author>Jem</author>
     <title>Books 4</title>
</book>
</books>

我试过这个(我知道这远非正确 - 所以请不要讨厌):

$(document).ready(function() {
 $('#click').click(function(){
    $.ajax({
      url : 'books.xml',
      dataType : 'xml',
    success : parse,
     });

   function parse(xml){
     $('#content').append($(xml).find('authour').text());
       }
   });
 });

如何使用jQuery访问每个authours id规范。 (对不起,如果我搞砸了解释它!:))。

1 个答案:

答案 0 :(得分:1)

可以使用带有$.ajax$.get$.post的jQuery加载xml。 一旦你使用jQuery,它有一个方法$.parseXML

$.ajax({url: 'file.xml', method: 'GET', dataType: 'xml'}).done(function (xml) {
  var xmlDoc = $.parseXML( xml );
  var author = $(xmlDoc).find('book[id="jem"]').find('author');
  $('#content').append('<span>' + author.text() + '</span>');
});

在这种情况下,服务器应使用正确的mime类型Content-type: "text/xml"进行响应