Javascript 如何从路由获取JSON响应?
我有以下路线:Javascript 如何从路由获取JSON响应?,javascript,python,json,flask,get,Javascript,Python,Json,Flask,Get,我有以下路线: @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响应,该方法是
@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,
"name": "Chevrolet",
"price": 4385.96
}
]
使用
XMLHttpRequest
时,可以在XMLHttpRequest
实例的responseText
属性中找到响应主体。你把阅读回复的位置放错了
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);
旁注。现在我们有了,它是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();
});
我不知道info变量来自哪里。对于js部分,现在我建议您使用fetch API:对我不起作用(似乎
console.log(data);
也不起作用),您能告诉我更多关于请求的信息吗?查看开发人员工具的网络选项卡以查找更多详细信息。