简体   繁体   English

使用AJAX POST请求存储数值数据

[英]Storing Numeric Data using AJAX POST Request

I'm trying to store numeric data (integers) using a simple AJAX request: 我正在尝试使用一个简单的AJAX请求存储数字数据(整数):

function sendRating(rating) {
    var userRating = rating.value;
    $.ajax({
          url: '/rating',
          type: 'POST',
          data: JSON.stringify({
              "rating": userRating
          }),
          contentType: 'application/json; charset=utf-8',
          dataType: 'json',
          success: (...)
    });
}

This function is attached to buttons that have values (1,2,3,4,5). 此功能附加到具有值(1,2,3,4,5)的按钮上。 Because I'm using JSON.stringify , the numbers get converted to a string when I check the records in the database. 因为我使用的是JSON.stringify ,所以当我检查数据库中的记录时,数字将转换为字符串。 When I return the results in the database, they look like this: { "rating": "4" } 当我在数据库中返回结果时,它们看起来像这样: { "rating": "4" }

How can I avoid this? 如何避免这种情况?

Form values are strings. 表单值是字符串。 You're telling it to send a string. 您要告诉它发送一个字符串。

JSON.stringify doesn't convert numbers to strings (and running it in the console to test your assumptions would show that immediately). JSON.stringify不会将数字转换为字符串(并且在控制台中运行以测试您的假设会立即显示出来)。

There are many options, but here's one of them: 有很多选择,但这是其中之一:

data: JSON.stringify({
  rating: parseInt(userRating, 10)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM