从javascript函数问题返回json
我试图从javascript函数返回自定义json对象我的代码如下 html从javascript函数问题返回json,javascript,json,Javascript,Json,我试图从javascript函数返回自定义json对象我的代码如下 html <input type='checkbox' name='chk[]' value='1'>1 <input type='checkbox' name='chk[]' value='2'>2 <input type='text' id='txt' value='' /> <input id='btn' type='button' value='click' />
<input type='checkbox' name='chk[]' value='1'>1
<input type='checkbox' name='chk[]' value='2'>2
<input type='text' id='txt' value='' />
<input id='btn' type='button' value='click' />
我需要的结果如下
{
chk: [{val: 1}, {val: 2}],
txt: 'test'
};
您需要在json对象中定义chk变量。因为chk是未定义的,所以它不知道它是一个数组
var json = {};
$('#btn').click(function(){
console.log(getdata());
});
function getdata(){
json.chk = [];
$('input:checked').each(function(i){
json.chk.push({ val : $(this).val()});
});
json.txt = document.getElementById("txt").value;
return json;
}
chk不是定义为数组,您需要首先定义为数组,然后将值推入数组
var json = {};
$('#btn').click(function(){
console.log(getdata());
});
function getdata(){
$('input:checked').each(function(i){
if(json.chk)
{
json.chk.push({val:$(this).val()})
}
else
{
json.chk=[];
json.chk.push({val:$(this).val()})
}
});
json.txt = document.getElementById("txt").value;
return json;
}
我还引用了这个问题“添加项的答案,它返回类似以下内容的
{chk:[{0:[val:1]},{1:[val:2]}],txt:'test'}代码>0和1是数组的索引。它们不是数组中对象的一部分。输出正是您在问题中提到的。如果要检查、迭代数组并打印出值,则不会看到0和1
var json = {};
$('#btn').click(function(){
console.log(getdata());
});
function getdata(){
$('input:checked').each(function(i){
if(json.chk)
{
json.chk.push({val:$(this).val()})
}
else
{
json.chk=[];
json.chk.push({val:$(this).val()})
}
});
json.txt = document.getElementById("txt").value;
return json;
}