我有这段代码:
var d = [];
$('.sortable li').each( function() {
var book_id = $(this).attr('book-id');
var order = $(this).index() + 1;
d.push({'book_id': book_id, 'order': order});
});
console.log(d);
$.post('/books/reorder', d, function(resp) {
alert(resp);
});
当我console.log(d);
时,一切看起来都很棒,但当我将其发布到我的服务器时,请求表单数据为空。
这里有什么我想念的吗?
谢谢!
答案 0 :(得分:5)
数据仅采用PlainObject或String
的docs状态Type: PlainObject or String A plain object or string that is sent to the server with the request.
您正在尝试发送数组。如果你把它作为一个对象,你可以传递它
$.post('/books/reorder', {data:d},function(resp) {
如果您阅读有关数据属性的jquery.ajax文档
data Type: PlainObject or String Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting
重要的部分是Object must be Key/Value pairs.