开发者

Extracting CDATA Using jQuery

开发者 https://www.devze.com 2022-12-25 01:23 出处:网络
It looks like this has been asked before, but the answers do not appear to work for me.I am outputting information from a local XML file, but the description elements is not being output because it is

It looks like this has been asked before, but the answers do not appear to work for me. I am outputting information from a local XML file, but the description elements is not being output because it is enclosed in CDATA - if I remove the CDATA portion then things work fine.

Here is my code:

$(document).ready(
  function() {
    $.get('test.xml',
      function($info) {
        objInfo = $($info);

        objInfo.find('item').slice(0,5).each(
          function() {
            var Guid = $(this).find('guid').text();
            var Title = $(this).find('title').text();
            var Description = $(this).fi开发者_运维技巧nd('description').text();
            $('#Content').append(
              "<p><a href='" + Guid + "'>" + 
              Title + "</a>&nbsp;" +
              Description +
              "</p>"
            )
          }
        );

      },
      'xml'
    );
  }
)

Any idea how I can successfully extract Description information that is wrapped in CDATA?

Thanks -

george


I just spent the last few hours on something very similar, and what worked for me was explicitly setting the content type to "text/xml" and "xml" on sending / receiving sides. I.e,

Server side:

...
response.setContentType("text/xml");
...

Client / jQuery side:

... 
$.ajax({
  type: 'POST',
  url: 'myAjaxHandler',
  processData: false,
  data: message,
  contentType: 'text/xml', 
  dataType: 'xml',
  success: function(xml, textStatus) {
   var myVar= $(xml).find('interestingNode').text();
   $('#someId').append(myVar); 
  },
  error: function(xhr, textStatus, errorThrown) {
   ...
  }
 });

...

Not sure if both are required.

From the documentation, if you don't specify the content type anywhere, jQuery will try to "guess" what you are sending, and in my case I had HTML embedded in CDATA.

0

精彩评论

暂无评论...
验证码 换一张
取 消