jQuery AJAX提交表单并输出返回值

前端部分:

<!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() {
		
	}
}

?>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值