响应 Ajax 请求

2021-12-08 15:12:02
admin
1472
最后编辑:admin 于 2022-11-23 10:53:38

control 中内置了一个 send() 方法,通常用于 Ajax 请求中,输出 data 数据。

该方法的参数 $data 通常是一个关联数组,对于 Ajax 请求,send 方法会将数组转化为 Json 数据格式输出。

对于非 Ajax 请求,也可以使用 send 方法。通过设置 result 、message、locate 来返回响应数据。

注:result 取值为 success 或 fail

以一个简单的用户登录验证为例:

control 中,验证用户登录时输入的账号密码:

if (!empty($_POST))
{
$account  = trim($this->post->account);
$password = $this->post->password;
$user = $this->user->login($account, $password);
if(!$user) $this->send(array('result'=>'fail', 'message' => $this->lang->user->loginFailed));

$this->send(array('result'=>'success', 'locate' => $this->createLink($this->config->default->module)));
}

视图页面中对应的 Ajax 请求:

$("submit").on("click", function(event) {
    $.ajax(
    {
        contentType: 'application/x-www-form-urlencoded',
        type:"POST",
        url:"createLink("shop","index")",
        data:"username=" + $("#username").val() +"&password=" + $("#password").val(),
        dataType:"json",
        success:function(data)
        {
            if(data.result == "success") return location=data.locate;
            if(data.result == "fail") return alert(data.message);
        },
    })
});

具体可参考 send 方法的声明代码:

    /** 
     * 直接输出data数据,通常用于ajax请求中。
     * Send data directly, for ajax requests.
     *
     * @param  misc   $data 
     * @param  string $type 
     * @access public
     * @return void
     */
    public function send($data, $type = 'json')
    {
        if($type != 'json') die();
        $data = (array) $data;
        if(helper::isAjaxRequest() or $this->viewType == 'json') print(json_encode($data)) and die(helper::removeUTF8Bom(ob_get_clean()));
        
        /**
         * 响应非ajax的请求。
         * Response request not ajax. 
         */
        if(isset($data['result']) and $data['result'] == 'success')
        {
            if(!empty($data['message'])) echo js::alert($data['message']);
            $locate = isset($data['locate']) ? $data['locate'] : (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '');
            if(!empty($locate)) die(js::locate($locate));
            die(isset($data['message']) ? $data['message'] : 'success');
        }
        
        if(isset($data['result']) and $data['result'] == 'fail')
        {
            if(!empty($data['message']))
            {
                $message = json_decode(json_encode((array)$data['message']));
                foreach((array)$message as $item => $errors) $message->$item = implode(',', $errors);
                echo js::alert(strip_tags(implode(" ", (array) $message)));
                die(js::locate('back'));
            }
            die('fail');
        }
    }