为什么我的对象键未定义且值不是(Why are my object keys undefined and the values are not)
我正在构建这个简单的对象数组
var myData = $('.form-group input:not(.add), .form-group select').map(function() { return { 'id': this.id, 'value': this.value }; }).get();如果我在console.log中输出,我可以看到键和值
但是当我尝试在$ .ajax调用中使用myData时,它会丢弃键吗?
例如
$.ajax({ url: site + form, type: 'POST', async: false, data: myData, success: function(response) { //do stuff } });这是POST标头:
I have this simple object array being built
var myData = $('.form-group input:not(.add), .form-group select').map(function() { return { 'id': this.id, 'value': this.value }; }).get();If I console.log the output I can see the keys and the values
but as soon as I try to use myData in an $.ajax call, it drops the keys?
e.g.
$.ajax({ url: site + form, type: 'POST', async: false, data: myData, success: function(response) { //do stuff } });This is the POST headers:
最满意答案
发布数据时,您的数据应如下所示:
{ key1: val1, key2: val2 }在您的情况下,您的数据看起来像:
[ { id: key1, value: val1 }, { id: key1, value: val1 } ]以下是如何构建myData变量的修复:
var myData = {} $('select').each(function() { myData[this.id] = this.value; }) console.log(myData) $.ajax({ url: '', type: 'POST', async: false, data: myData, success: function(response) { //do stuff } });<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="a"><option>1</option></select> <select id="b"><option>2</option></select>When posting data your data should look like:
{ key1: val1, key2: val2 }In your case, your data looked like:
[ { id: key1, value: val1 }, { id: key1, value: val1 } ]Here is a fix for how to build your myData variable:
var myData = {} $('select').each(function() { myData[this.id] = this.value; }) console.log(myData) $.ajax({ url: '', type: 'POST', async: false, data: myData, success: function(response) { //do stuff } });<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="a"><option>1</option></select> <select id="b"><option>2</option></select>
更多推荐
发布评论