繁体   English   中英

jquery post 方法的问题

[英]Issues with jquery post method

我正在尝试制作一个简单的 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",
            data: {},
            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", function(){ //post request goes here console.log("mouse clicked!") $.post({ url: "http://localhost:5000/hello_world", data: {}, success: function(data){ formatReturnedData(data) console.log(data) console.log('hi bruh') }, dataType: 'string' }) }) }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM