问题描述
我正在尝试制作一个简单的hello world应用程序以测试连接前端和后端。后端是一个简单的烧瓶应用程序。
这是单击按钮时执行的JS:
function mouseAction() {
let helloWorldButton = document.getElementById('btn')
helloWorldButton.addEventListener("click",function(){
//post request goes here
console.log("mouse clicked!")
$.post({
url: "http://localhost:5000/hello_world",data: {},success: function(data){
formatReturnedData(data)
},dataType: 'string'
})
console.log(data)
console.log('hi bruh')
})
}
我知道该请求已被服务器接收,因为我的守护程序记录了该请求:
但是'hi bruh'或'data'从未打印到控制台,我在做什么错?任何帮助表示赞赏。
解决方法
您的请求格式不正确。您的console.log
应该位于成功回调函数的内部。并且'string'
不是有效的dataType
值。
尝试以下方法:
$.post({
url: 'http://localhost:5000/hello_world',data: {},success: function(data) {
formatReturnedData(data);
console.log(data);
console.log('hi bruh');
},dataType: 'json'
});
有关更多详细信息,请参见文档https://api.jquery.com/jquery.post/
,数据仅存在于成功函数之内
function mouseAction() {
let helloWorldButton = document.getElementById('btn')
helloWorldButton.addEventListener("click",function(){
//post request goes here
console.log("mouse clicked!")
$.post({
url: "http://localhost:5000/hello_world",success: function(data){
formatReturnedData(data)
console.log(data)
console.log('hi bruh')
},dataType: 'string'
})
})
}
,
默认情况下,jQuery ajax请求异步工作。在这种情况下,您在服务器请求console.log在服务器响应之前执行之后,将console.log放在服务器上。如果将console.log放入成功的回调函数中,则该问题将解决。例如
function mouseAction() {
let helloWorldButton = document.getElementById('btn')
helloWorldButton.addEventListener("click",dataType: 'string'
})
})
}