使用XML文档而不是String

时间:2014-03-17 22:15:52

标签: javascript jquery xml

好的,所以我得到了这个Javascript代码,我用它来用HTML显示一些XML。

   var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
  xmlDoc = $.parseXML( xml ),
  $xml = $( xmlDoc ),
  $title = $xml.find( "title" );

// Append "RSS Title" to #someElement
$( "#someElement" ).append( $title.text() );

// Change the title to "XML Title"
$title.text( "XML Title" );

// Append "XML Title" to #anotherElement
$( "#anotherElement" ).append( $title.text() );

但我想使用XML文件而不是字符串。 我试过这样的事情:

   var xml = $.get("myfile.xml"),
  xmlDoc = $.parseXML( xml ),
  $xml = $( xmlDoc ),
  $title = $xml.find( "title" );

// Append "RSS Title" to #someElement
$( "#someElement" ).append( $title.text() );

// Change the title to "XML Title"
$title.text( "XML Title" );

// Append "XML Title" to #anotherElement
$( "#anotherElement" ).append( $title.text() );

(myfile.xml将包含与字符串相同的文本) 对不起,如果这是非常明显的,我是一个新手,谈到JavaScript:D PS:如果我忘记提及的话,请在评论中告诉我!

1 个答案:

答案 0 :(得分:1)

$.get默认为异步

使用:

$.get("myfile.xml", function (xml) {
  xmlDoc = $.parseXML( xml ),
  $xml = $( xmlDoc ),
  $title = $xml.find( "title" );

  // Append "RSS Title" to #someElement
  $( "#someElement" ).append( $title.text() );

  // Change the title to "XML Title"
  $title.text( "XML Title" );

  // Append "XML Title" to #anotherElement
  $( "#anotherElement" ).append( $title.text() );
});