繁体   English   中英

如何从ajax post()返回值?

[英]How to return value from ajax post()?

我创建了一个可以调用 javascript 函数的简单按钮。

<button type="submit" id="likebtn" onclick="likedpost(this)" data-postid="<%=blog._id%>" data-author="<%=user.username%>">Like</button>
                
<span id="likescounter"><%=blog.likes%></span>  

这是下面的javascript函数。

function likedpost(el){
var id = el.dataset.postid;
var author = el.dataset.author;
var request = $.ajax({
type: "POST",
url: "api/index/like",
data: {id: id, author:author},
async:false,
dataType:"html",
success: function(){
  findingnumberoflikes(data)//here I want to use the return data after post.
  console.log("action performed successfully")
}

});
}
function findingnumberoflikes(data)
 {
  console.log("the data returned is "+ data);
 }

在服务器端

 app.post('/api/index/like', (req,res)=>{
 // After updating the database , How can I return some value from here.
 });

谢谢!

上述解决方案对客户端有好处。 我假设您还想知道如何从服务器发送响应。

客户端:

success: function(data) {
    findingnumberoflikes(data);
    console.log("action performed successfully");
}

服务器端:

app.post('/api/index/like', (req,res)=>{
    // After updating the database , How can I return some value from here.
    // here is how you can send
    res.json({ data: "test data", success: true });
});

你的代码:

    success: function(){
        findingnumberoflikes(data)//here I want to use the return data after post.
        console.log("action performed successfully")
    }

工作解决方案:

    success: function(data){
        findingnumberoflikes(data);
        console.log("action performed successfully");
    }

此外,我建议您添加以下内容:

    error: function(e){
        console.log("Error occured: " + e);
    }

所以你的代码看起来像这样:

    success: function(data){
        findingnumberoflikes(data);
        console.log("action performed successfully");
    },
    error: function(e){
        console.log("Error occured: " + e);
    }

暂无
暂无

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

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