为什么我的对象键未定义且值不是(Why are my object keys undefined and the values are not)

编程入门 行业动态 更新时间:2024-10-19 06:19:09
为什么我的对象键未定义且值不是(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> 
  
 

更多推荐

本文发布于:2023-08-04 23:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1424551.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   未定义   object   values   undefined

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!