如何从Node.js中的Ajax发布返回成功 [英] How to return success from ajax post in Node.js
本文介绍了如何从Node.js中的Ajax发布返回成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的功能:
exports.saveAction = function (req, res) {
var conn = mysql.createConnection({
host : nconf.get("database:host"),
//port: 3306,
user : nconf.get("database:username"),
password : nconf.get("database:password"),
database : nconf.get("database:database"),
multipleStatements: true,
//ssl: 'Amazon RDS'
});
var action = req.body;
conn.query('UPDATE actions SET ? WHERE Id = ?',
[action, action.Id], function (err, result) {
conn.end();
if (err) throw err;
res.writeHead(200, { "Content-Type": "application/json" });
res.end("Updated Successfully");
});
};
我返回"200",但是它总是在如下所示的error子句中返回:
and I am return "200", but it always returns in the error clause shown below:
$.ajax({
url: "/api/action/SaveAction",
type: "PUT",
data: ko.toJSON(self.stripDownObj()),
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log(result);
if(result.status == 200){
self.isEditMode(!self.isEditMode());
}
},
error: function(result){
console.log(result);
}
});
注意:sql查询成功并且确实保存了数据.
Note: the sql query is successful and does save the data.
推荐答案
当您期望JSON时返回JSON
By returning JSON when you're expecting JSON
res.end('{"success" : "Updated Successfully", "status" : 200}');
然后
$.ajax({
....
datatype: "json", // expecting JSON to be returned
success: function (result) {
console.log(result);
if(result.status == 200){
self.isEditMode(!self.isEditMode());
}
},
error: function(result){
console.log(result);
}
});
在Node中,您始终可以使用JSON.stringify来获取有效的JSON
In Node you could always use JSON.stringify to get valid JSON as well
var response = {
status : 200,
success : 'Updated Successfully'
}
res.end(JSON.stringify(response));
Express还支持这么做
Express also supports doing
res.json({success : "Updated Successfully", status : 200});
它将对象转换为JSON并自动为您传递适当的标头.
where it will convert the object to JSON and pass the appropriate headers for you automatically.
这篇关于如何从Node.js中的Ajax发布返回成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文