如何从Node.js中的ajax帖子返回成功

时间:2014-04-02 19:06:02

标签: javascript jquery ajax node.js express

我有这样的功能:

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",但它总是在下面显示的错误条款中返回:

$.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查询成功并保存数据。

1 个答案:

答案 0 :(得分:27)

当你期待JSON时返回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

var response = {
    status  : 200,
    success : 'Updated Successfully'
}

res.end(JSON.stringify(response));

Express也支持

res.json({success : "Updated Successfully", status : 200});

它会将对象转换为JSON并自动为您传递相应的标题。