AJAX POST将数字作为字符串

时间:2015-12-29 00:44:26

标签: javascript ajax string numbers

我的AJAX POST请求由于某种原因将numeric数据发送到我的服务器string ...这是我的数据和AJAX请求:

var data = {
        projectId: $("#projectId").val(),
        startDate: $("#startDate").val(),
        endDate: $("#endDate").val(),
        num_auto_tests: Number($("#num_auto_tests").val()),
        num_manual_tests: Number($("#num_manual_tests").val()),
        num_passed_tests: Number($("#num_passed_tests").val()),
        num_failed_tests: Number($("#num_failed_tests").val()),
        num_unran_tests: Number($("#num_unran_tests").val()),
        test: 3
    };

AJAX查询:

$.ajax({
        type: "POST",
        dataType: "json",
        url: "/addreport/+ data.projectId",
        data: data,
        success: function() {
            console.log('success');
        }
    });

console.log(typeof(data.num_auto_tests)); //returns `number`

服务器端返回:

{ projectId: 'FDIC-88445',
  startDate: '',
  endDate: '',
  num_auto_tests: '3',
  num_manual_tests: '3',
  num_passed_tests: '3',
  num_failed_tests: '3',
  num_unran_tests: '3',
  test: '3' } 

如您所见,应该是数字的值是服务器端的所有字符串......

有谁知道发生了什么?

提前致谢!

4 个答案:

答案 0 :(得分:3)

您的服务器收到HTTP协议中的帖子,难怪您的服务器端收到一个字符串,因为您正在执行的操作不是类型安全的。这实际上是预期的行为,如果您希望元素变为数字,那么将参数转换为数字,确切的方法取决于您使用的服务器端语言/框架。

编辑: 您可以做两件事来解决您的问题:

  1. 您可以创建一个数字处理程序/转换器,如下所示:

    function detectNumeric(obj) { for (var index in obj) { if (!isNaN(obj[index])) { obj[index] = Number(obj[index]); } else if (typeof obj === "object") { detectNumeric(obj[index]); } } }

  2. 并为您想要以这种方式处理的任何对象调用此函数,或

    1. 将参数作为JSON传递并在服务器上解码。
    2. var my_object = {
      
        position: 1,
        id: "500",
        text: "hello world",
        greeting: "100, good day to you",
        book: "nineteen eighty four"
      
      };
      
      
      // iterates over an object's properties 
      // and converts numbers as strings to numbers
      function detectNumeric(obj) {
        for (var index in obj) {
          // if object property value *is* a number, like 1 or "500"
          if (!isNaN(obj[index])) {
            // convert it to 1 or 500
            obj[index] = Number(obj[index]);
          }
          // to do: explain what this does
          // else if (typeof obj === "object") {
          //  detectNumeric(obj[index]);
          // }
        }
      
        console.log(my_object)
      }
      
      // call function
      detectNumeric(my_object);

答案 1 :(得分:1)

我认为POST请求的默认内容类型是对其进行url-encode。这实质上将所有内容都转换为字符串值,并按原样检索。根据您使用的服务器端体系结构,可以使用不同的内容类型(或随后手动支持),例如使用可以保留对象结构和类型的内容类型application/json

答案 2 :(得分:0)

我用JSON.stringify解决了这个问题。 PFB我的Ajax呼叫:

var settings = {
  "url": "http://localhost:12345/docker/scale",
  "type": "POST",
  "headers": {
    "Content-Type": "application/json"
  },
  "data": JSON.stringify({ "scale": { "desired-instances": 123 } })
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

通过执行此值仅作为整数传递,因此不需要在服务器端代码中进行任何更改。

答案 3 :(得分:0)

这是我的解码器,它可以处理多维数组/对象

//running the object through tests
function tryParsingType(unknownObj) {
    if (unknownObj.constructor.name === "String" && !isNaN(parseFloat(unknownObj)))
        return parseFloat(unknownObj);
    else if (unknownObj.constructor.name === "String" && (unknownObj === "true" || unknownObj === "false"))
        return unknownObj === "true";
    else if (unknownObj.constructor.name === "Array" || unknownObj.constructor.name === "Object")
        tryParsingTypes(unknownObj);
    return unknownObj;
}

//works for generic objects and arrays
function tryParsingTypes(genericObj) {
    var type = genericObj.constructor.name;
    if (!(type === "Array" || type === "Object"))
        return;
    var keys = Object.keys(genericObj);
    for (var i = 0; i < keys.length; i++) {
        var object = genericObj[keys[i]];
        genericObj[keys[i]] = tryParsingType(object);
    }
}

//example code below
var testObj = {
    "key5": "-1",
    "key6": "-132.3123",
    "key7": "3421",
    "key10": "true",
    "key11": "false",
    "key12": 'true',
    "key13": 'false',
    "key14": {
        "key1": {
            "key1": "true",
            "key2": {
                "key1337": "-432.2342",
                "key321": {
                    "key1": "-1231.2",
                    "key2": "false"
                }
            }
        },
        "key2": ["true", "false"],
        "key3": 2.5,
        "key4": "3",
        "key5": "40",
        "key6": "40.99441"
    },
    "key15": [1, 2, 2.5, "3", "40", "40.99441"]
};
var testArr = [1, 2, 3, 4, 5, "6", "7", "8", "9", "10", true, false, "true", "false", {
        "key1": 1,
        "key2": 2,
        "key3": 2.5,
        "key4": "3",
        "key5": "40",
        "key6": "40.99441"
    }, [1, 2, 2.5, "3", "40", "40.99441", ["1", "2"]]];

tryParsingTypes(testObj);
tryParsingTypes(testArr);

console.log({
    "testObj": testObj,
    "testArr": testArr
});