javascript - 从 javascript 函数问题返回 json

标签 javascript json

我正在尝试从 javascript 函数返回自定义 json 对象,我的代码如下

Fiddle

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/

相关文章:

javascript - 过滤 OrionJS 中某个角色可以查看的文档

json - Logstash 输出 elasticsearch - 动态生成索引名称

使用 R 从 API 检索图片

javascript - 我有一个从起草者那里获得的 json 对象,我只想要模式

json - 如何将特殊格式的数据导入Elasticsearch?

javascript - 红外线未返回 1 作为正确值

javascript - 我如何滚动到 Qooxdoo virtualist 的最后一项

javascript - 测量同级元素的总高度

Javascript/PHP 重定向

sql - 如何选择与 json 字段数组中的值匹配的记录?