解析xmlhttpresponse以检索值

时间:2016-06-24 18:56:54

标签: parsing xml-parsing xmlhttprequest

我已经设法阅读了回复,但我已经被困了几个小时,现在试图获得“平衡”值。

如何解析23号码? (这是这种情况下的平衡)

<!DOCTYPE html>
<html>
<body>

<p id="data"></p>

<script>

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
     document.getElementById("data").innerHTML =
     xhttp.responseText;

        
    }
  };
  xhttp.open("GET", "http://api.reimaginebanking.com/accounts/576d55170733d0184021f510?key=081e7c77daa22967b857b3152e3ff2f1", true);
 xhttp.send();


</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

以下是如何使用JSON.parse检索余额的示例:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        var objResp = JSON.parse(xhttp.responseText);
        document.getElementById("data").innerHTML = objResp.balance // 23
    }
};
xhttp.open("GET", "http://api.reimaginebanking.com/accounts/576d55170733d0184021f510?key=081e7c77daa22967b857b3152e3ff2f1", true);
xhttp.send();

或者您甚至可以使用eval方法,但该解决方案不太可靠,因为响应可能包含将要执行的恶意代码:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        var objResp = eval('('+xhttp.responseText+')');
        document.getElementById("data").innerHTML = objResp.balance // 23
    }
};
xhttp.open("GET", "http://api.reimaginebanking.com/accounts/576d55170733d0184021f510?key=081e7c77daa22967b857b3152e3ff2f1", true);
xhttp.send();