Reputation: 31
If i don't use the var productOj and i output the response. innerHTML= this.response; I will respond this{"detail":"this is detail", "link":"/link/here"} so the response come back in json but i want to access individual detail and link and output them somewhere else.
function getProduct(productName) {
if (productName == "0") {
document.getElementById("instr_text").innerHTML = "Please Select A Product";
return;
} else {
// document.getElementById("orderSummary").innerHTML = str;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//document.getElementById("orderSummary").innerHTML = "success";
var productObj = JSON.parse(this.responseText);
document.getElementById("detail").innerHTML = productObj.detail;
} else {
//document.getElementById("orderSummary").innerHTML = "failure" + this.readyState + this.status;
}
};
xmlhttp.open("GET", "getinfo.php?productName=" + productName,true);
xmlhttp.send();
}
}
Upvotes: 2
Views: 43
Reputation: 2090
It might look something like this.
var productObj = JSON.parse(this.responseText);
var productHtml = "";
productObj.forEach(product => productHtml += "<p>" + product.detail + "</p>")
document.getElementById("detail").innerHTML = productHtml;
What you're doing is going through each element in your productObj
array and creating the HTML that you're looking for. Once you have the blob of html you want, you append it in the div of your choice. You can repeat / modify this process to access link
as well.
Upvotes: 1