我一直在尝试理解 AJAX,并且我确实设法发送单条数据。但是当我尝试发送数组时,什么也没有发生。我尝试将其格式化为 JSON,但在这方面并没有真正成功。我在 stackoverflow 上搜索过任何提示和技巧的组合,几乎已经成功了。
下面是无需进行大部分数学计算即可获取价格的 JS:
var data = [];
$('[id$="-subtotal"]').each(function () {
subtotal = some_math;
id = some_ID_Number;
data['id-' + String(id)] = subtotal
});
$.ajax({
url: '/test/',
type: 'POST',
dataType: "JSON",
data: {
'prices': data,
'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val()
},
success: function (data) {
}
});
我一直在尝试使用以下方式访问数组:
request.POST.get('prices')
最佳答案
您没有正确使用
$.each()
。试试这个:$.each($('[id$="-subtotal"]'), 函数(键,元素){ 小计 = some_math;
id = 某个 ID 号; data['id-' + String(id)] = 小计 });
- 您应该将
data
声明为对象,而不是数组。数组只能有数字键。对象可以具有包含其他字符的键。如果您console.log(data)
,您将看到data
(如果它是对象)将包含数据,如果初始化为数组,则该数据将为空。所以试试这个:
var data = {};
$.each($('*'), function() {
subtotal = Math.random() * 100;
id = Math.random() * 100;
data['id-' + String(id)] = subtotal
});
console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于jquery - 通过 Ajax 传递关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44801428/