前端部分:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form id="form1">
<p>Last name: <input type="text" name="name" /></p>
<input id="btn"type="submit" value="Submit" />
</form>
<script src="//jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function(){
<span style="white-space:pre"> </span>$("#btn").click(function() {
<span style="white-space:pre"> </span>var params=$("#form1").serialize();
<span style="white-space:pre"> </span>$.ajax({
<span style="white-space:pre"> </span>type: "post",
<span style="white-space:pre"> </span>data:params,
<span style="white-space:pre"> </span>dataType:"json",//返回值类型,建议不要默认自行定义
<span style="white-space:pre"> </span>//dataType: "binary",
<span style="white-space:pre"> </span>async: false,
<span style="white-space:pre"> </span>timeout: 30000,
<span style="white-space:pre"> </span>url: 'http://localhost/TP/index.php/Admin/Conf/viewUser',
<span style="white-space:pre"> </span>success: function(result){//result为接收返回值的参数名,可自行修改
<span style="white-space:pre"> </span>var s = result.data;
<span style="white-space:pre"> </span> <span style="white-space:pre"> </span>alert(s);
<span style="white-space:pre"> </span>},
<span style="white-space:pre"> </span>error: function(x, e) {
<span style="white-space:pre"> </span>// alert(x.readyState);
<span style="white-space:pre"> </span>alert(e);
}
<span style="white-space:pre"> </span>});
<span style="white-space:pre"> </span>});
});
</script>
</body>
</html>
此脚本将表单输入值序列化后传至后台,后台使用ThinkPHP框架,接收了POST方式传入的参数name,并将$_POST['name']的值以JSON格式打包后返回,前端已预先指定接收数据类型为JSON,并以result为返回值变量名称进行输出。
后台代码
<?php
namespace Admin\Controller;
use Think\Controller;
/**
*
* @author XFX
* user:add/change/delete,auth:add/change/delete
*/
class ConfController extends Controller {
public function Index() {
$this->display('Template/Admin/Conf.html');
}
public function viewUser() {
//$var=$_POST;
$data['data'] =$_POST['name'];
$this->ajaxReturn($data);
}
public function changeUser() {
}
public function delUser() {
}
}
?>