thinkPHP5框架中怎么利用ajax与后台数据交互?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
前端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax交互</title>
<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script>
function ajaxPost(){
var formData = $("#myform").serialize();
//serialize() 方法通过序列化表单值,创建 URL 编码文本字符串,这个是jquery提供的方法
$.ajax({
type:"post",
url:"{:url('Index/index/reg')}", //数据传输的控制器方法
data:formData,//这里data传递过去的是序列化以后的字符串
success:function(data){
$("#content").append(data);//获取成功以后输出返回值
}
});
}
</script>
</head>
<body>
<form id="myform">
<!--这里给表单起个id用于获取表单并序列化-->
<input type="text" name="account" />
<input type="password" name="passwd" />
<button onclick="ajaxPost()">---------</button>
</form>
<div id="content">
</div>
</body>
</html>后端代码:
public function reg($account,$passwd){
if($account == '123'){
return json("ajax成功!".$account."---".$passwd);
}else{
return json("你输出的是其他值:".$account."---".$passwd);
}
}看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注天达云行业资讯频道,感谢您对天达云的支持。