我需要将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}});
由于
答案 0 :(得分:3)
$.post
没有发送JSON,它使用application/x-www-form-urlencoded
格式。此格式不区分数据类型,所有内容都以字符串形式发送。如果参数应该是一个整数,则需要在服务器代码中对其进行转换。
此外,在JSON中,对象键始终是字符串。
为了得到你想要的结构,它应该是:
$.post('/cart/update.js', {updates: updates});
您正在添加额外级别的嵌套,因为{updates}
是{updates: updates}
的ES6简写,因此您发送{updates: {updates: updates}}
。