简体   繁体   中英

how to get element from XML using javascript

I have to change my project form XML to JavaScript (at least some parts of it). So I had construction like this :

$xml = simplexml_load_file("http://...);
$profile = $xml->profile;   
$user_id = $profile->user_id;

Now I wanted to translate this into JavaScript so I used :

var xmlHttp_subscribe = new XMLHttpRequest();
xmlHttp_subscribe.onreadystatechange=postCall;
xmlHttp_subscribe.open("GET","http://...",true);
xmlHttp_subscribe.send();

and now function postCall()

function postCall(){
  var t = document.getElementsByName("MY_API").value;
  alert('t'+t);
  var p = document.getElementsByName("profile").value;
  alert('p'+p);
  var h = document.getElementsByName("user_id").value;
//...//
 }

The XML is under my http:// is like that :

<MY_API>
  <profile>
    <user_id>the_user_id</user_id>
  </profile>
</MY_API>

What I would like to do is to get this 'the_user_id' part as string in plain text. Does any one have any idea how to do this? Am I looking in the good direction?

Thanks for any kind of help.

There is no function "getElementsByName". What you need is getElementsByTagName.

Check this link out, it should be what you're looking for

As suggested by Pineda, the right function name is getElementsByTagName , and in addition the right property name is not "value" but nodeValue , so you should use

function postCall(){
  var h = document.getElementsByTagName("user_id").nodeValue;
}

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