当前位置: 首页 > 文档资料 > DoitPHP 帮助文档 >

5.3 实例演示三

优质
小牛编辑
127浏览
2023-12-01

学习目标:

通过一个简单的AJAX调用实例,了解DoitPHP框架在数据交互的具体操作方式。

创建文件:

1、新建Controller文件为:IndexController, 文件路径为:application/controllers/IndexController.php, 内容如下:

/**
* DoitPHP 演示实例三
*
* @author tommy
* @copyright Copyright (C) www.doitphp.com All rights reserved.
* @version $Id: Index.php 1.0 2020-11-10 18:55:39Z tommy $
* @package Controller
* @since 1.0
*/
namespace controllers;

use doitphp\core\Controller;

class IndexController extends Controller {

/**
* 表单提交(首页)
*
* @access public
* @return void
*/
public function indexAction() {

$this->display();
}

/**
* ajax后台处理
*
* @access public
* @return void
*/
public function ajax_handleAction() {

$userName = $this->post('user_name');
$password = $this->post('user_password');

if(!$userName || !$password){
$this->ajax(false, '用户名和密码不能为空!');
}

$this->ajax(true, '操作成功!', array('target'=>'http://wwww.doitphp.com'));
}
}

由上面代码可知,只有indexAction()需要视图文件,而ajax_handleAction(),返回的是json数据,无需视图文件。所以新建视图路径为:application/views/index/index.php。内容如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>演示实例三:AJAX交互</title>
<script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function(){
$("#submit-btn").click(function(){
var userName=$("#user-name").val();
var password=$("#user-password").val();
if(userName==""){
alert('用户名不能为空!');
$("#user-name").focus();
return false;
}
$.post("<?php echo $this->getActionUrl('ajax_handle'); ?>",
{"user_name":userName, "user_password":password}, function(json){
if(json.status==true){
//当有网址跳转或页面刷新时
if(json.data.target){
if(json.data.target=='refresh'){
location.reload();
} else {
location.href=json.data.target;
}
}
} else {
if(json.msg!='') {
alert(json.msg);
}
}
}, 'json');
});
});
</script>
</head>

<body>
<fieldset>
<legend>用户登陆:</legend>
<label>用户名:</label>:
<input type="text" name="user_name" id="user-name"><br>
<label>密码:</label>:
<input type="password" name="user_password" id="user-password"><br>
<input type="button" name="submit-btn" id="submit-btn" value="登陆">
</fieldset>
</body>
</html>

运行测试:

在浏览器地址栏里输入项目的入口文件网址,输入数据,提交表单。测试下效果...