【问题标题】:Manipulating a variable containing XML with jQuery?使用 jQuery 操作包含 XML 的变量?
【发布时间】:2009-09-28 21:12:18
【问题描述】:

我正在使用 AJAX 接收 XML 响应,然后我需要对其进行操作。通过使用 jQuery 的上下文选项,我可以从 XML 数据中进行选择,但我仍然无法写入。

$('blah', xml)

选择xml就好了,但是

$('blah', xml).removeClass( 'myClass' )

似乎对 xml 变量没有任何作用!如何实现我正在寻找的功能?

例子:

var data = null;

$(document).ready(function(){
$.ajax({
   type:"GET",
   url:"blah/blah.jsp",
   success:function(msg)
   {
      data = msg;
      init();
   }
});

function init()
{
   $('#myElement', data).removeClass('hidden');//removeAttr('class') also fails
}

示例 xml 文件:

<root>
<div>
<!--lots of content -->
</div>
<div>
<p id = "myElement<->" class = "hidden">
  Test!
</p>
</div>
</root>

【问题讨论】:

  • 我们可以看看 XML 文件吗?
  • addClass/removeClass 是特定于 HTML 的,它们修改名为 class 的属性。你能告诉我们 removeAttr 是否有效吗?

标签: javascript jquery xml ajax


【解决方案1】:

这对我有用。

<html>
<head>
  <title>Test Page</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
    <script type="text/javascript">
    $(function()
    {
    var data = null;
    $.ajax({
        type:"GET",
        url:"sample.xml",
        dataType: 'xml',
        success:function(msg)
        {
           init( $(msg) );
        }
    });

    function init( $xml )
    {
      var $myElement = $xml.find( '#myElement' );
      $myElement.removeAttr( 'class' );
      console.log( $myElement );
    }
    });
    </script>
</head>

<body>

</body>
</html>

这里是 sample.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>
<div>

</div>
<div>
<p id = "myElement" class = "hidden">
  Test!
</p>
</div>
</root>

所以请确保您使用 "xml" 作为 dataType 选项进行请求,并且您的 JSP 页面返回的内容具有正确的 Content-Type 标头 (text/xml)

【讨论】:

  • 反复点击投票,希望它可能会投到 100。 jsp 响应标头上的内容类型。多么微妙的错误。
  • 还要注意可能需要使用 msg.d 而不仅仅是 msg。 encosia.com/2009/02/10/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-10
  • 2015-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
相关资源
最近更新 更多