2015-05-08 100 views
-1

的問題我想檢索郵件和密碼,並將它們顯示爲<p>元素中的json格式。問題是,當我點擊提交,沒有任何反應..是我的代碼錯了嗎?json_encode

<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

JavaScript沒有json_encode,這是PHP函數 – Almis

+0

我的意思是在結束一個標籤代碼 。 –

回答

1

在JavaScript中,你使用JSON.stringify,不json_encode(這是PHP)轉換東西JSON:

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 
}); 
+1

非常感謝你!問題解決了:D –