简体   繁体   中英

Storing Numeric Data using AJAX POST Request

I'm trying to store numeric data (integers) using a simple AJAX request:

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). Because I'm using JSON.stringify , the numbers get converted to a string when I check the records in the database. When I return the results in the database, they look like this: { "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).

There are many options, but here's one of them:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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