I have the following route:
@api_blueprint.route("/cars", methods=["GET"])
@jwt_required()
def get_inventory():
with session_scope():
cars = dbu.list_cars()
return jsonify(CarDetails(many=True).dump(cars))
I have to get the JSON response in a GET method which is a list of cars and insert into my html page. I'm also not sure whether the code after the comment is true, it was one of my attempts to do something.
let xhr = new XMLHttpRequest();
let method = "GET";
const url = "http://127.0.0.1:5000/cars";
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
/*get here JSON response from a route somehow*/
document.getElementsByClassName("car_name").innerHTML = info.info[1]
document.getElementsByClassName("car_price").innerHTML = info.info[2]
}
else if (xhr.readyState === 4 && xhr.status !== 200){
alert(JSON.parse(xhr.responseText).message);
window.location.reload();
}
};
xhr.send(null);
}
The response is following:
[
{
"carId": 1,
"name": "Chevrolet",
"price": 3547.14
},
{
"carId": 2,
"name": "Lotus",
"price": 4558.47
},
{
"carId": 3,
"name": "Chevrolet",
"price": 4385.96
}
]
When using XMLHttpRequest
the response body can be found in the responseText
property of the XMLHttpRequest
instance. You've misplaced the position of where you read the response.
let xhr = new XMLHttpRequest();
let method = "GET";
const url = "http://127.0.0.1:5000/cars";
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
// getElementsByClassName returns an array of elements.
// querySelector returns a single element based on a CSS selector.
document.querySelector(".car_name").innerHTML = data.info[1]
document.querySelector(".car_price").innerHTML = data.info[2]
} else {
// statusText shows the status message of the request.
alert(xhr.statusText);
window.location.reload();
}
}
};
xhr.send(null);
Sidenote. Nowadays we have the Fetch API , which is the modern equivalent of the XMLHttpRequest
interface. Though it is useful to know how XMLHttpRequest
works, I'd recommend learning fetch
as well.
The example below is the fetch
equivalent of the code above.
let method = "GET";
const url = "http://127.0.0.1:5000/cars";
fetch(url, {
method,
headers: {
"Content-Type": "application/json"
}
}).then(response => {
if (!response.ok) {
throw new Error(`Fetching JSON went wrong - ${response.statusText}`);
}
return response.json();
}).then(data => {
console.log(data);
document.querySelector(".car_name").innerHTML = data.info[1]
document.querySelector(".car_price").innerHTML = data.info[2]
}).catch(error => {
alert(error);
window.location.reload();
});
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.