在 JQuery ajax POST 调用中传递非字符串数据

Passing non-string data in a JQuery ajax POST call

本文关键字:字符串 数据 JQuery ajax POST 调用      更新时间:2023-09-26

这是我在SO和Google上已经在这里和那里看到的问题,但是无法为我的情况找到实际的解决方案,也无法自己弄清楚。

我正在将数据从javascript应用程序发送到Node js服务器,用于对数据库的查询。

通话数据:

var cDate = new Date();
var name = "get";
var method = "POST";
var data = {
        "db": "alerts",
        "params": {
            "selector":{
                "$or": [
                    {
                        "expires.year":{
                            "$gt": cDate.getFullYear()
                        }
                    },
                    {
                        "expires.year":{
                            "$eq": cDate.getFullYear()
                        },
                        "expires.month":{
                            "$gt": (cDate.getMonth()+1)
                        }
                    },
                    {
                        "expires.year":{
                            "$eq": cDate.getFullYear()
                        },
                        "expires.month":{
                            "$eq": (cDate.getMonth()+1)
                        },
                        "expires.day":{
                            "$gte": cDate.getDate()
                        }
                    }
                    ]
                },
    "sort":["created.year:number","created.month:number","created.day:number"]
}
    };

实际调用:

var jqXHR = $.ajax({
    url:baseURL+"/"+name,
    dataType:"json",
    crossDomain:true,
    data:data,
    method:method,
    success: function(data,status,xhr){
        busyIndicator.hide();
        console.log("success, status: "+status);
        console.log("--> RESPONSE: "+JSON.stringify(data));
        if (callbackSuccess!="") window[callbackSuccess](data);
    },
    error:function(xhr,status,err){
        busyIndicator.hide();
        console.log("error, status: "+status);
        console.log(err);
        genericFailure("Errore nella chiamata al service: "+err);           
    }
}); 

一切正常(.ajax 自行"字符串化"我的 JSON 数据),除了日期也转换为字符串的事实,因此我随后的数据库查询失败(因为数据库试图面对字符串与数字)。我已经尝试发送

parseInt(<value I want to stay a number>)

但当然它不起作用,因为内容稍后会字符串化。

在这里我读到不可能将号码作为号码发送,我需要在服务器端转换它们,但问题是如果我通过邮递员拨打相同的电话

{
    "db": "alerts",
    "params": {
    "selector":{
        "$or": [
            {
            "expires.year":{
                "$gt": 2016
              }
            },
            {
            "expires.year":{
                "$eq": 2016
              },
            "expires.month":{
                "$gt": 2
              }
            },
            {
            "expires.year":{
                "$eq": 2016
              },
            "expires.month":{
                "$eq": 2
              },
            "expires.day":{
                "$gte": 29
              }
            }
        ]
        },
"sort":["created.year:number","created.month:number","created.day:number","created.hour:number","created.min:number"]
    }
}

它按计划进行,数字保持数字,所以这是可能的。

有人知道如何从我的javascript POST调用中做到这一点吗?

我提前感谢。

更新

在拨打电话之前,我尝试串化我发送的数据:

data:JSON.stringify(data)

服务器端我可以正确查看数据,如果我像这样记录它

console.log(JSON.stringify(request.body))

但是如果我尝试用它制作一个对象并使用它,即

var bodyStr = JSON.stringify(request.body)
var bodyObj = JSON.parse(bodyStr)
console.log("db is " + bodyObj.db)

我得到"无法读取未定义的属性'db'"。

如果我尝试在收到请求后直接记录数据,即

console.log(request.body);

我得到[对象对象],如果我尝试解析它而不先字符串化它,我会得到

SyntaxError: Unexpected token o

感谢所有发表评论的人,我无法给予您适当的认可,因为您在评论中在这里和那里解决了它。

我能够通过更改代码中的件事来使其工作(数字保持数字):

1) 在发送数据之前将数据字符串化

2)将contentType设置为所需的值,在我的例子中为"应用程序/json"

var jqXHR = $.ajax({
    url:baseURL+"/"+name,
    contentType:"json",
    crossDomain:true,
    data:data,
    method:method,
    success: function(data,status,xhr){
        busyIndicator.hide();
        console.log("success, status: "+status);
        console.log("--> RESPONSE: "+JSON.stringify(data));
        if (callbackSuccess!="") window[callbackSuccess](data);
    },
    error:function(xhr,status,err){
        busyIndicator.hide();
        console.log("error, status: "+status);
        console.log(err);
        genericFailure("Errore nella chiamata al service: "+err);           
    }
});

服务器端我可以正确访问对象,而无需任何额外的解析/字符串化,例如

var dataBaseName = request.body.db;

最后,正如 Kevin B 指出的那样,您还需要设置

dataType: "json"

在调用中,如果您希望返回一个对象,否则您将得到一个字符串化的对象。这是"json",而不是"application/json",因为它是contentType。