我正在尝试从 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' />
js
var json = {};
$('#btn').click(function(){
console.log(getdata());
});
function getdata(){
$('input:checked').each(function(i){
json.chk = $(this).val();
//json.chk.push({"val": $(this).val()}); gives error Uncaught TypeError: Cannot call method 'push' of undefined
});
json.txt = document.getElementById("txt").value;
return json;
}
我需要如下结果
{
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;
}
关于javascript - 从 javascript 函数问题返回 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13283356/