如何解决如何从路由获取 JSON 响应?
我有以下路线:
@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))
我必须在 GET 方法中获取 JSON 响应,该方法是一个汽车列表并插入到我的 html 页面中。 我也不确定评论后面的代码是否正确,这是我尝试做的事情之一。
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);
}
回复如下:
[
{
"carId": 1,"name": "Chevrolet","price": 3547.14
},{
"carId": 2,"name": "Lotus","price": 4558.47
},{
"carId": 3,"price": 4385.96
}
]
解决方法
使用 XMLHttpRequest
时,可以在 responseText
实例的 XMLHttpRequest
属性中找到响应正文。你放错了阅读回复的位置。
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);
旁注。现在我们有 Fetch API,它是 XMLHttpRequest
界面的现代等价物。尽管了解 XMLHttpRequest
的工作原理很有用,但我还是建议您学习 fetch
。
下面的例子是上面代码的 fetch
等价物。
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();
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。