javascript – 如何从Node.js中的ajax post返回成功

前端之家收集整理的这篇文章主要介绍了javascript – 如何从Node.js中的ajax post返回成功前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这样的功能
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查询是成功的,并且保存数据.

解决方法

当您期待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,并自动传递适当的标题.

猜你在找的Ajax相关文章