AJAX POST 将数字作为字符串发送

Tru*_*ran 5 javascript string ajax 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
    };
Run Code Online (Sandbox Code Playgroud)

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`
Run Code Online (Sandbox Code Playgroud)

服务器端返回:

{ 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' } 
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,应该是数字的值在服务器端都是字符串......

有谁知道发生了什么事吗?

提前致谢!

Atu*_*hav 7

我曾经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);
});
Run Code Online (Sandbox Code Playgroud)

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


Laj*_*pad 4

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

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

  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]); } } }

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

  1. 以 JSON 形式传递参数并在服务器上解码。

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);
Run Code Online (Sandbox Code Playgroud)