当使用jQuery发送JSON数据时,实际上可能会发布数组而不是预期的JSON对象,这通常与数据序列化方式和服务器端处理有关。
.serialize()
和.serializeArray()
方法默认会将表单数据序列化为URL编码的字符串或数组格式。Content-Type: application/json
,jQuery可能会使用默认的application/x-www-form-urlencoded
。$.ajax({
url: 'your-endpoint',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ key: 'value', anotherKey: 'anotherValue' }),
success: function(response) {
console.log(response);
}
});
$('#yourForm').submit(function(e) {
e.preventDefault();
var formData = {};
$(this).serializeArray().forEach(function(item) {
formData[item.name] = item.value;
});
$.ajax({
url: $(this).attr('action'),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(formData),
success: function(response) {
console.log(response);
}
});
});
var formData = new FormData($('#yourForm')[0]);
$.ajax({
url: 'your-endpoint',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response) {
console.log(response);
}
});
application/json
。console.log(JSON.stringify(yourData))
检查数据格式。通过以上方法,你可以确保jQuery正确发送JSON对象而非数组到服务器端。
没有搜到相关的文章