简体   繁体   中英

Can't get xml element text value using jquery

I have a an ajax call that returns an xml response. I want to get the value of one of the elements in this response , ie 'Some Name'. The problem is that there are 5 or 6 of these tags in the response. Is there a way to get the value of just the first one? It's always the first one I will want to use. Here is some of the code:

var xmlData = '<userId internalId="Some Number"xmlns:platformCore="urn:core_2013_1.platform.webservices.netsuite.com"><platformCore:name>Some Name</platformCore:name></userId>';
var $xml = $(xmlData);
var $user = $xml.find("platformCore:name").text();
alert($user);

I also have a js fiddle here: http://jsfiddle.net/8FqRd/5/

EDIT: FIX BELOW:

My ajax response was already in xml form, so no need to parse. This line worked for me:

var user = $(xmlResponse).find("userId").find("name").text();

The main jQuery function doesn't parse XML correctly: it treats it as HTML, with variable results. Use $.parseXML() instead.

I'm not sure how jQuery deals with XML, particularly namespaces. I would guess not at all. However, searching for elements by local name rather than fully qualified name seems to work.

Demo: http://jsfiddle.net/timdown/8FqRd/6/

var xmlData = '<userId internalId="Some Number"xmlns:platformCore="urn:core_2013_1.platform.webservices.netsuite.com"><platformCore:name>Some Name</platformCore:name></userId>';
var $xml = $( $.parseXML(xmlData) );
var $user = $xml.find("name").text();
alert($user);

As Tim pointed out you need to use $.parseXML(xmlData)

However as your xml tag has a : in it, you will have to escape it.

var xmlData = '<userId internalId="Some Number" xmlns:platformCore="urn:core_2013_1.platform.webservices.netsuite.com"><platformCore:name>Some Name</platformCore:name></userId>';
var xml = $.parseXML(xmlData);
var $xml = $(xml);
var $user = $xml.find("platformCore\\:name").text(); // you need to escape the : 
alert($user);

Check http://jsfiddle.net/8FqRd/7/ for a demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM