Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

javascript - parse xml response with jQuery

HI all,
I use jQuery to parse my xml?responses.

I have this xml :

<?xml version="1.0" encoding="UTF-8"?>
<response status="ok">
  <client_id>185</client_id>
</response>

And i want to get "client_id" value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To fix the expected response data type to XML right in your request, set the dataType parameter to "xml". If you don't, jQuery uses the response headers to make a guess.

It is supported on the $.ajax() function as part of the options object, as well as on $.get() and $.post():

jQuery.ajax( options )
jQuery.get( url, data, callback, type )
jQuery.post( url, data, callback, type )

So you could do this:

$.ajax({
  type: 'GET',
  url: "foo.aspx",
  data: {
    key: "value"
  },
  dataType: "xml",
  success: function (xml){
    var clientid = $(xml).find('client_id').first().text();
    alert(clientid);
  }   
});

Note that as of jQuery 1.5 you can use a nicer version of the above Ajax request:

$.get("foo.aspx", {
  key: "value"
})
.done(function (xml){
  var clientid = $(xml).find('client_id').first().text();
  alert(clientid);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...