试图在json中打印一个关键变量

时间:2016-03-09 13:37:00

标签: javascript jquery json ajax jsp

伙计我是新手所以请帮助我..我正在尝试在json中打印变量键..但它不起作用..这是我的代码



<body>
  <input type="text" name="name">
  <button type="button" id="btn" onclick="constructJson(document.getElementById(" name "))">Click Me!</button>
  <script type="text/javascript">
    function constructJson(jsonKey) {
      var jsonObj = {
        "key1": "5"
      };
      jsonObj[jsonKey] = "2";
      alert(jsonObj);
    }
  </script>
</body>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

双引号内不能有双引号,你应该使用输入值而不是DOM节点:

onclick="constructJson(document.getElementById('name').value)"

你需要设置输入的id:

<input type="text" name="name" id="name">

显示JSON,你需要使用JSON.stringify:

function constructJson(jsonKey){
	var jsonObj = {"key1": "5"};
   jsonObj[jsonKey] = "2";
   alert(JSON.stringify(jsonObj));
}
<input type="text" name="name" id="name">
<button type="button" id="btn" onclick="constructJson(document.getElementById('name').value)" >Click Me!</button>

答案 1 :(得分:0)

我建议你将代码与html分开:

&#13;
&#13;
window.onload=function() {
  document.getElementById('btn').addEventListener('click', constructJson, false);
}
function constructJson(eleName) {
  var jsonKey = document.getElementsByName('name')[0].value.trim();
  if (jsonKey.length == 0) {
    alert('insert a name');
    document.getElementsByName('name')[0].focus();
    return;
  }
  var jsonObj = {
    "key1": "5"
  };
  jsonObj[jsonKey] = "2";
  alert(JSON.stringify(jsonObj, 4, 4));
}
&#13;
<input type="text" name="name">
<button type="button" id="btn">Click Me!</button>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

<body>
<input type="text" name="name" id="name">
<button type="button" id="btn" onclick="constructJson(document.getElementById('name').value)">Click Me!</button>
<script type="text/javascript">
    function constructJson(jsonKey) {
        var jsonObj = {
            "key1": "5"
        };
        jsonObj[jsonKey] = "2";
        console.log(jsonObj);
        alert('{"key1":"5","'+jsonKey+'":"2"}');
        alert(jsonObj);
    }
</script>
</body>