javascript - 如何从 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 });
});
推荐阅读
- python - Tensorflow 2.0 将 keras 模型转换为 .pb 文件
- python - 在 DataFrame 中将字符串转换为整数
- spring-boot - Spring Boot + Hibernate Search:忽略所需的索引状态?
- python - dict中元组的莫名长度
- mysql - 应该向哪个添加 shipping_charges?
- python - 修剪字符串直到任何指定的字符
- mysql - 为什么这个更新声明没有更新?
- socket.io - 将从一个 socket.io 服务器接收到的数据发送到 Web 套接字客户端
- django - 用于激活/停用管理站点的 Django 管理命令
- javascript - Wordpress 文件上传错误:加载资源失败:服务器响应状态为 404(未找到)