简体   繁体   中英

Unable to get value from json response this.responseText?

Unable to get value from json response Here is my html.

index html

<!DOCTYPE html>
<html>
<head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<h1>The XMLHttpRequest Object</h1>

<button type="button" onclick="loadDoc()">Request data</button>
<br>
<br>

<p id="demo"></p>
<p id="demo1"></p>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML ="JSON  =  "+this.responseText;
      document.getElementById("demo1").innerHTML = "first name =  "+this.responseText.fname;
    }
  };
  xhttp.open("POST", "/test.php", true);
  xhttp.setRequestHeader("Content-type", "application/json");
  xhttp.send();
}
</script>

</body>
</html>

and test.php

<?php
echo '{"fname":"sumith","lname":"emmadi"}'
?>

when I click request data button it will send a POST request to "/test.php" and get response as

{"fname":"sumith","lname":"emmadi"}

I want to get value of fname but it is showing undefined

image

You need to parse the JSON into an object before you can extract the specific property values. eg

if (this.readyState == 4 && this.status == 200) {
  var data = JSON.parse(responseText);
  document.getElementById("demo1").innerHTML = "first name =  "+ data.fname;
}

You will get a response inside xhttp.responseText or this.responseText . And to get fname and lname, first parse result using JSON.parse and get fname , lname out of it using Destructuring assignment

const { fname, lname } = JSON.parse(xhttp.responseText);

// To show in DOM
document.getElementById("demo").innerHTML ="JSON  : <pre> " + xhttp.responseText + "</pre>";

document.getElementById("demo1").innerHTML = "first name =  " + fname;

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