json_encode的问题

时间:2015-05-08 11:34:46

标签: javascript json

我想检索邮件和密码,并在<p>元素中将它们显示为json格式。问题是,当我点击提交时,没有任何反应..我的代码有问题吗?

<html>
<head>

</head>
<body>

<script>
function myfunction() {
var mail = document.getElementById("mail1").value;
        var pass = document.getElementById("password1").value;
        //document.getElementById("ici").innerHTML = mail + " " + pass  ;
        tab['mail'] =  mail;
        tab['password'] =  password;
        var output = json_encode(tab);
        document.getElementById("ici").innerHTML = output;
    }

</script>

Mail: <input type="text"  name="mail" id="mail1">
password: <input type="text"  name="password" id="password1">
<button onclick="myfunction()" > submit</button>

<p>ici: <span id="ici"></span></p>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

在JavaScript中,您使用JSON.stringify将内容转换为JSON,而不是json_encode(即PHP):

var output = JSON.stringify(tab);

但引用的代码会失败,因为您无法在任何地方定义tab,并且您已使用password而不是pass(您提供的名称)变量)。你可能意味着:

var mail = document.getElementById("mail1").value;
var pass = document.getElementById("password1").value;
var output = JSON.stringify({
    mail: mail,
    password: pass
});
document.getElementById("ici").innerHTML = output;

或者更简洁(但不那么容易调试):

document.getElementById("ici").innerHTML = JSON.stringify({
    mail: document.getElementById("mail1").value,
    password: document.getElementById("password1").value
});