Re: 用 Json 来实现 PHP 与 JavaScript 间数据交换
json_encode.html
[code]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>json:From javascript To php</title>
<script src="json2.js" type="text/javascript"></script>
<script type="text/javascript">
function JSON_test(o)
{
var user = {
name:document.getElementById('txt_name').value,
email:document.getElementById('txt_email').value,
password:document.getElementById('txt_password').value
}
var json_string = JSON.stringify(user);
document.getElementById('txt_json').value=json_string;
alert("点击确定后将提交表单");
o.submit();
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="json_encode.php" onsubmit="JSON_test(this);return flase;">
<label for="txt_name">姓名</label>
<p><input type="text" name="txt_name" id="txt_name" /></p>
<label for="txt_email">邮箱</label>
<p><input type="text" name="txt_email" id="txt_email" /></p>
<p><label for="txt_password">密码</label></p>
<p><input type="text" name="txt_password" id="txt_password" /></p>
<p><input type="text" name="txt_json" id="txt_json" />
<label for="button"></label>
<input type="submit" name="button" id="button" value="JSON" />
</p>
</form>
</body>
</html>
[/code]
这里javascript扁平化需要一个插件:http://www.json.org/json2.js,通过JSON.stringify(str)将对象扁平化然后传送给php。