search
HomeBackend DevelopmentPHP TutorialIntroduction to ajax asynchronous partial refresh in thinkphp

Abstract: ThinkPHP is a low-end framework commonly used by small websites, but unprofessional documentation and coding make it easy for users to only know the surface but not the inside. Here we only use jquery to implement ajax in thinkphp which has not been mentioned in the official documentation. A brief summary of asynchronous interaction.

Environment: ThinkPHP3.2.3, jQuery

##Reading directory:

Text:

In general websites, you need to use jquery or other frameworks (such as angular) to handle front-end and back-end data interaction. In thinkphp, there are also some built-in functions in the background for data interaction (such as ajaxReturn()). The purpose of this article is to open up the front-end and back-end data interaction process from jquery ajax to thinkphp.

Foreword:

1.thinkphpAboutajax Introduction

1.1 ajaxReturn: The

\Think\Controller

class provides ajaxReturnMethod is used for AJAXAfter calling returns data to Client (view, template, js, etc.) . And supports JSON, JSONP, XML and EVALFour ways to accept data from the client (defaultJSON). (Link: http://document.thinkphp.cn/manual_3_2.html#ajax_return)

Configuration method: convention The default encoding type defined in .php is DEFAULT_AJAX_RETURN => 'JSON',

Analysis: ajaxReturn() call json_encode() Convert the value into json data storage format. Commonly used values ​​are arrays.

Note: The value being encoded can be any type except a resource(Resource file).All string data must be UTF-8 encoded.(Link:http://php.net/manual/en/function.json-encode.php

Example:

$data['status'] = 1;

$data['content'] = 'content';

$this->ajaxReturn($data);

1.2 Request type:

Built-in system There are some constants used to determine the request type, such as:

Constant Description

IS_GET

Determine whether it is GETSubmit by method

IS_POST

Determine whether it is submitted by POSTSubmit by method

IS_PUT Judge whether it is submitted in PUT

IS_DELETE Judge whether it is DELETEMethod to submit

IS_AJAX Judge whether it is AJAXSubmit

REQUEST_METHOD Current Submission type

Purpose: On the one hand, different logical processing can be made for the request type, and on the other hand, unsafe requests can be filtered. (Link:http://document.thinkphp.cn/manual_3_2.html#request_method

Use Method:

class UserController extends Controller{

public function update(){

if (IS_POST){

$User = M( 'User');

                             $User->create();     

                                                                                                                                                                    ##Save completed

');                                                                                                                                                ');

}

}}

1.3

Jump and redirection:

The function is relatively useless. In

ajax asynchronous interactive partial refresh, there is no need to jump with text prompts. (Link: http://document.thinkphp.cn/manual_3_2.html#page_jump_redirect

)

二, jQuery Ajax Introduction:

##2.1

Official website’s introduction to

jQuery.ajax()

jQuery.ajax() method is used to execute AJAX (asynchronous HTTP

) request. (Link:http://www.jquery123.com/jQuery.ajax/)Syntax: $.ajax({name:value, name:value, ... }), this parameter specifies one or more names of the AJAX request

/ value pair. Common parameters: type (Default

: 'GET')

Type: StringRequest method ("POST" or

"GET") , the default is

"GET". Note :Other HTTP request methods, such as PUT and DELETE can also be used, but is only supported by some browsers.

url (Default: Current page address)

Type: String

The address to send the request.

async (Default: true)1.8 version has been abandoned Use)

Type: Boolean

Under the default settings, all requests are asynchronous requests (that is to say, this is the default setting is true ). If you need to send synchronous requests, set this option to false .

data

Type: Object, String

Data sent to the server. Will be automatically converted to request string format. GET The request will be appended to URL . See the processData option description to disable this automatic conversion. The object must be in the format "{key:value}". If this parameter is an array, jQuery will be automatically converted into a multi-valued query character with the same name according to the value of the traditional parameter. String (See description below). Note: For example, {foo:["bar1", "bar2"]} is converted to '&foo=bar1&foo=bar2'.

dataType (Default: Intelligent Guess (xml, json, script, or html))

Type: String

The data type expected to be returned by the server. If not specified, jQuery will automatically make intelligent judgments based on HTTP packageMIME information, such as The XML MIME type is recognized as XML. In 1.4, JSON will generate a JavaScript object, andscript will execute this script. The data returned by the server will then be parsed based on this value and passed to the callback function. Example :

"json": Execute the response result as JSON and return a JavaScriptObject. In jQuery 1.4 , data in JSON format is parsed in a strict manner, if there is an error in the format, jQuery will be rejected and throw a parsing error exception. (See json.org for more information on the correct JSON format.)

error

Type: Function(jqXHR jqXHR, String textStatus, String errorThrown)

This function is called when the request fails. There are the following three parameters: jqXHR (before jQuery 1.4.x is XMLHttpRequest) Object and description occurrence A string of the error type and the caught exception object. If an error occurs, the error message (the second parameter) may not only be null, but also may be "timeout", "error", "abort " , and "parsererror". When an HTTP error occurs, errorThrown receives the text portion of the HTTP status , such as: "Not Found" (not found) or "Internal Server Error." (server internal error). Starting from jQuery 1.5, is set in error to accept an array composed of functions . Each function will be called in turn. Note: This handler is not called for cross-origin scripts and requests of the form JSONP. This is an Ajax Event.

success

Type: Function( Object data, String textStatus, jqXHR jqXHR )

The callback function after the request is successful. This function passes 3 parameters: the data returned from the server and processed according to the dataType parameters, a string describing the status ;Also jqXHR ( before jQuery 1.4.x XMLHttpRequest) object. In jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event

OthersjQuery-ajax-settings, see:http://www.jquery123.com/#jQuery-ajax-settings

Example:

injsSend id as data to the server, save some data to the server, and notify the user once the request is completed. If the request fails, alert the user.

var menuId = $("ul.nav").first().attr("id");
var request = $.ajax({
  url: "script.php",
  type: "POST",
  data: {id : menuId},
  dataType: "html"
});
request.done(function(msg) {
  $("#log").html( msg );
});
request.fail(function(jqXHR, textStatus) {
  alert( "Request failed: " + textStatus );
});

Note: success and ## can also be used here in ajax() The #error parameter determines whether the request result is successful or failed, and performs the next step.

2.2 js and json

2.2.1 json

What is:

JSON

JavaScript Object Notation (JavaScript Object Notation) . It is a language-independent syntax for storing and exchanging textual information.

2.2.2 jsonajax的关系?

在上面关于jquery.ajax的介绍中提到了,json可以作为一个ajax函数的dataType,这样数据就会通过json语法传输了。(链接:http://www.cnblogs.com/haitao-fan/p/3908973.html

jqueryajax函数中,只能传入3种类型的数据:

>1.json字符串:"uname=alice&mobileIpt=110&birthday=1983-05-12"

>2.json对象:{uanme:'vic',mobileIpt:'110',birthday:'2013-11-11'}

>3.json数组:

[
    {"name":"uname","value":"alice"},
    {"name":"mobileIpt","value":"110"},   
    {"name":"birthday","value":"2012-11-11"}
]

2.2.3 json的编解码和数据转换:

2.2.2中提到的json对象是更方便与js数组、js字符串或php数组、php字符串进行数据转化的json类型。下面以json对象为例讲解一下json对象与jsphp的数据类型转化。

json对象转化成数组:

<script type="text/javascript">
        var jsonStr = &#39;[{"id":"01","open":false,"pId":"0","name":"A部门"},{"id":"01","open":false,"pId":"0","name":"A部门"},{"id":"011","open":false,"pId":"01","name":"A部门"},{"id":"03","open":false,"pId":"0","name":"A部门"},{"id":"04","open":false,"pId":"0","name":"A部门"}, {"id":"05","open":false,"pId":"0","name":"A部门"}, {"id":"06","open":false,"pId":"0","name":"A部门"}]&#39;;
      //  var jsonObj = $.parseJSON(jsonStr);
      var jsonObj =  JSON.parse(jsonStr)
        console.log(jsonObj)
     var jsonStr1 = JSON.stringify(jsonObj)
     console.log(jsonStr1+"jsonStr1")
     var jsonArr = [];
     for(var i =0 ;i < jsonObj.length;i++){
            jsonArr[i] = jsonObj[i];
     }
     console.log(typeof(jsonArr))
    </script>

想要将表单数据提交到后台,需要先从表单获取数据/数据集:

serializeserializeArray的区别是serialize()获取到序列化的表单值字符串,serializeArray()以数组形式输出序列化表单值。举例:

var serialize_string=$(&#39;#form&#39;).serialize();
得到:a=1&b=2&c=3&d=4&e=5
var serialize_string_array=$(&#39;#form&#39;).serializeArray();
得到:
[
  {name: &#39;firstname&#39;, value: &#39;Hello&#39;},
  {name: &#39;lastname&#39;, value: &#39;World&#39;},
  {name: &#39;alias&#39;}, // 值为空
]

相对来说,serializeArray()和最终想要得到的json数组更加相似。只不过需要将包含多个name-value形式json对象的json数组改写成'first_name':'Hello'形式的json对象。

这里使用第二种方法举例,可以起名为change_serialize_to_json()

var data = {};
$("form").serializeArray().map(function(x){
if (data[x.name] !== undefined) {
        if (!data[x.name].push) {
            data[x.name] = [data[x.name]];
        }
        data[x.name].push(x.value || &#39;&#39;);
    } else {
        data[x.name] = x.value || &#39;&#39;;
    }
});
输出:{"input1":"","textarea":"234","select":"1"}

 

完整流程:

var serialize=$(&#39;#form&#39;).serialize()结果(得到一个字符串,用serializeArray()更好,其中中文都会转换成utf8):
serial_number=SN2&result=%E9%9D%9E%E6%B3%95
var serialize_array=$(&#39;#form&#39;).serializeArray()结果(结果是json对象数组):
Array [ Object, Object ]
var data=change_serialize_to_json(serialize_array)的结果是(以第二种转换方法为例,结果是json对象):
Object {serial_number: "SN2", result: "非法" }
var json_data=JSON.stringify(data)(结果是json字符串):
{"serial_number":"SN2","result":"非法"}

js端将表单数据转化为json形式的其他函数:

json字符串转换为json对象:

eval("(" + status_process+ ")");
json字符串转化成json对象:
// jquery的方法
var jsonObj = $.parseJSON(jsonStr)
//js 的方法
var jsonObj =  JSON.parse(jsonStr)
json对象转化成json字符串:
//js方法
var jsonStr1 = JSON.stringify(jsonObj)
JSON.parse()用于从一个字符串中解析出json对象。JSON.stringify()相反,用于从一个对象解析出字符串。

str_replace() 函数用于替换掉字符串中的特定字符,比如替换掉数据转换后多余的空格、'/nbsp'

 注意:serializeserializeArray()函数在处理checkbox时存在无法获取未勾选项的bug,需要自己编写函数改写原函数,举例:

//value赋值为off是因为正常的serializeArray()获取到的勾选的checkbox值为on

$.fn.mySerializeArray = function () {
    var a = this.serializeArray();
    var $radio = $(&#39;input[type=radio],input[type=checkbox]&#39;, this);
    var temp = {};
    $.each($radio, function () {
        if (!temp.hasOwnProperty(this.name))
        {
            if ($("input[name=&#39;" + this.name + "&#39;]:checked").length == 0)
            {
                temp[this.name] = "";
                a.push({name: this.name, value: "off"});
            }
        }
    });
    return a;
};

三、使用js操作DOM实现局部刷新:

实现局部刷新的途径:

1、假设页面有查询form和结果table

2、点击查询form的提交,触 发js自定义的submit事件,在submit函数中对获取的表单数据检测后如果符合要求就传递给控制器,控制器从数据库获取结果数组后返回给ajaxsuccess。对返回给ajax的结果数组,可以创建一个refresh()函数,或直接在success中用jQuery(或其他js)操纵结果tableDOM),比如删除tbody节点下的所有内容,并将结果数组格式化后添加到tbody下面。

举例:

//1php中的form表单

<p class="modal fade hide" id="add_engineer_modal" tabindex="-1" role="dialog">
......
<form id="add_engineer_modal_form" class="form-horizontal">
<fieldset>
......
<button type="button" class="btn btn-primary" id="add_engineer_modal_submit" onclick="add_engineer_modal_submit()" >提交更改</button>
......
</fieldset>
</form>
</p>

 //2js校验表单并发起ajax

function add_engineer_modal_check_value() {
    //以edit_modal_check_value()为模板
    var serialize_array_object = $("#add_engineer_modal_form").mySerializeArray();
    var data = change_serialize_to_json(serialize_array_object);
    var check_results = [];
    check_results[&#39;result&#39;] = [];//保存错误信息
    check_results[&#39;data&#39;] = data;//保存input和select对象
    //check_employee_number是自定义判断员工号函数。
    if (check_employee_number(data[&#39;employee_number&#39;]) == false)
    {
        check_results[&#39;result&#39;].push("请输入有效的员工号(可选)");
    }
    return check_results;
}
 
function add_engineer_modal_submit() {
    var check_results = add_engineer_modal_check_value();
    if (check_results[&#39;result&#39;].length == 0)
    {
        var json_data = JSON.stringify(check_results[&#39;data&#39;]);   //JSON.stringify() 方法将一个JavaScript值转换为一个JSON字符串(ajax要求json对象或json字符串才能传输)
        $.ajax({
            type: &#39;POST&#39;,
            url: add_engineer_url, //在php中全局定义url,方便使用thinkphp的U方法
            data: {"json_data": json_data},            //ajax要求json对象或json字符串才能传输,json_data只是json字符串而已
            dataType: "json",
            success: function (data) {
                console.log("数据交互成功");
            },
            error: function (data) {
                console.log("数据交互失败");
            }
        });
    }
    else
    {
        //弹出错误提示alert
    }
    return 0;
}
 
3、控制器返回数组给js
public function add_engineer() {
if (IS_AJAX)
{
$posted_json_data = I(&#39;post.json_data&#39;);
$posted_json_data_replace = str_replace(&#39;"&#39;, &#39;"&#39;, $posted_json_data);
$posted_json_data_replace_array = (Array)json_decode($posted_json_data_replace);
   
   //处理数据库事务写入,通过判断写入结果来区分ajaxReturn的结果
  //可以将所有想要返回的数据放在一个数组中,比如新增的行id、插入数据库的操作是否成功
  //如果操作数据库成功就返回如下结果。
   $user_table->commit();
$data[&#39;result&#39;] = true;
$data[&#39;pk_user_id&#39;] = $data_add_user_result;
$this->ajaxReturn($data);
return 0;
}
}
改写js:
在js的ajax中,如果整个ajax正常交互,就会走success函数,否则会走error函数,一般情况下,error出现的原因都是传输的数据不符合要求。
在success中的data就是ajaxReturn中传输的数组,举例:
success: function (data) {
                if (data[&#39;result&#39;] == false)
                {
                    alert(data[&#39;alert&#39;]);
                }
                else
                {
                    $(&#39;#add_engineer_modal&#39;).modal(&#39;hide&#39;);
                    $(&#39;#user_list_table tr&#39;).eq(0).after(&#39;<tr></tr>&#39;);
                    //这里就可以使用data[&#39;pk_user_id&#39;]了。
                    $(&#39;#user_list_table tr&#39;).eq(1).append(&#39;<td>&#39;+data[&#39;pk_user_id&#39;]+&#39;</td>&#39;);
                }
            },

 四、总结

整个过程是:

php中编写页面中的表单、提交按钮等;

Add a checksum trigger function to the button event in php in js, in jsIn the function, if the format and content of the js object are correct, the controller url(php) initiates a ajax request;

The corresponding operation response in the controllerajax Request, perform database read and write operations after judging the data, and then make judgments on the database operation results, ajaxReturnReturnjsRequired array;

When ajax returns successfully, ajax in js Use js in success to rewrite (or initialize) the information that needs to be displayed.

This completes

ajaxAsynchronous partial refresh.

The above is the detailed content of Introduction to ajax asynchronous partial refresh in thinkphp. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
thinkphp是不是国产框架thinkphp是不是国产框架Sep 26, 2022 pm 05:11 PM

thinkphp是国产框架。ThinkPHP是一个快速、兼容而且简单的轻量级国产PHP开发框架,是为了简化企业级应用开发和敏捷WEB应用开发而诞生的。ThinkPHP从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的同时,也注重易用性。

一起聊聊thinkphp6使用think-queue实现普通队列和延迟队列一起聊聊thinkphp6使用think-queue实现普通队列和延迟队列Apr 20, 2022 pm 01:07 PM

本篇文章给大家带来了关于thinkphp的相关知识,其中主要介绍了关于使用think-queue来实现普通队列和延迟队列的相关内容,think-queue是thinkphp官方提供的一个消息队列服务,下面一起来看一下,希望对大家有帮助。

thinkphp的mvc分别指什么thinkphp的mvc分别指什么Jun 21, 2022 am 11:11 AM

thinkphp基于的mvc分别是指:1、m是model的缩写,表示模型,用于数据处理;2、v是view的缩写,表示视图,由View类和模板文件组成;3、c是controller的缩写,表示控制器,用于逻辑处理。mvc设计模式是一种编程思想,是一种将应用程序的逻辑层和表现层进行分离的方法。

实例详解thinkphp6使用jwt认证实例详解thinkphp6使用jwt认证Jun 24, 2022 pm 12:57 PM

本篇文章给大家带来了关于thinkphp的相关知识,其中主要介绍了使用jwt认证的问题,下面一起来看一下,希望对大家有帮助。

thinkphp扩展插件有哪些thinkphp扩展插件有哪些Jun 13, 2022 pm 05:45 PM

thinkphp扩展有:1、think-migration,是一种数据库迁移工具;2、think-orm,是一种ORM类库扩展;3、think-oracle,是一种Oracle驱动扩展;4、think-mongo,一种MongoDb扩展;5、think-soar,一种SQL语句优化扩展;6、porter,一种数据库管理工具;7、tp-jwt-auth,一个jwt身份验证扩展包。

thinkphp 怎么查询库是否存在thinkphp 怎么查询库是否存在Dec 05, 2022 am 09:40 AM

thinkphp查询库是否存在的方法:1、打开相应的tp文件;2、通过“ $isTable=db()->query('SHOW TABLES LIKE '."'".$data['table_name']."'");if($isTable){...}else{...}”方式验证表是否存在即可。

一文教你ThinkPHP使用think-queue实现redis消息队列一文教你ThinkPHP使用think-queue实现redis消息队列Jun 28, 2022 pm 03:33 PM

本篇文章给大家带来了关于ThinkPHP的相关知识,其中主要整理了使用think-queue实现redis消息队列的相关问题,下面一起来看一下,希望对大家有帮助。

thinkphp3.2怎么关闭调试模式thinkphp3.2怎么关闭调试模式Apr 25, 2022 am 10:13 AM

在thinkphp3.2中,可以利用define关闭调试模式,该标签用于变量和常量的定义,将入口文件中定义调试模式设为FALSE即可,语法为“define('APP_DEBUG', false);”;开启调试模式将参数值设置为true即可。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)