首页 > 解决方案 > 如何从 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.
 });

谢谢!

标签: javascriptjquery

解决方案


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

客户端:

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 });
});

推荐阅读