Home  >  Article  >  Backend Development  >  Introduction to ajax asynchronous partial refresh in thinkphp

Introduction to ajax asynchronous partial refresh in thinkphp

一个新手
一个新手Original
2017-09-12 09:51:012213browse

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