我需要将id
和quantity
作为整数发送。我将其定义为整数,但是由于某些原因,当我尝试发布它时,它会将id
作为字符串发布。
我在这里缺少一些简单的东西,只是不知道是什么。.如何将id
和quantity
都发送为整数?我的代码如下:
var id = parseInt(identifier, 20);
var quantity = parseInt(amount, 10);
var updates = {};
updates[id] = quantity;
$.post('/cart/update.js', {updates: {updates}});
帖子中的JSON应该如下所示:
$.post('/cart/update.js', {updates: {40076307207: 1}});
谢谢
最佳答案
$.post
不发送JSON,它使用application/x-www-form-urlencoded
格式。这种格式不能区分数据类型,所有内容都以字符串形式发送。如果参数应为整数,则需要在服务器代码中对其进行转换。
另外,在JSON中,对象键始终是字符串。
为了获得所需的结构,它应该是:
$.post('/cart/update.js', {updates: updates});
您要添加一个额外的嵌套级别,因为
{updates}
是{updates: updates}
的ES6缩写,因此您要发送{updates: {updates: updates}}
。