Home > Web Front-end > JS Tutorial > body text

Summary of knowledge points of jQuery's AJAX

零到壹度
Release: 2018-03-24 14:23:40
Original
1413 people have browsed it

This time the editor has compiled the knowledge points of AJAX in jQuery for everyone. The following is a summary of the knowledge points. Let’s take a look.

1. AJAX concept
Asynchronous Javascript And XML(Asynchronous JavaScript and XML)
AJAX is not a language, but a way to create interactive web applications Web development technology
AJAX is a combination of Javascript, XHTML and CSS, DOM, XML and XSTL, XMLHttpRequest and other technologies
1. Use XHTML+CSS to standardize presentation;
2. Use XML and XSLT for data Exchange and related operations;
3. Use the XMLHttpRequest object for asynchronous data communication with the Web server;
4. Use Javascript to operate the Document Object Model (network document object model) for dynamic display and interaction;
5.Use JavaScript binds and processes all data
What is XML?
XML refers to Extensible Markup Language (EXtensible Markup Language)
XML is a markup language, very similar to HTML
XML is designed to transmit Data, not display data
The XML tag is not predefined. You need to define the labels yourself.
XML is designed to be self-describing.
XML is a recommended standard by W3C
What is XSLT?
XSLT refers to XSL Transformations [1]
XSLT is the most important part of XSL
XSLT can convert one type of XML document into another type of XML document
XSLT uses XPath in XML Navigation in the document

##User operation process:
User browser->JavaScript instantiation XmlHttpRequest object->AJAX engine->http request->web server->backend business system
System return process :
Backend business system->Backend server->web server->HTML, XML, JSON data->AJAX engine->HTML+CSS (Wel browser)->User browser

##3. AJAX advantages and disadvantages:
AJAX asynchronous processing advantages:
Reduce the burden on the server, AJAX generally only obtains only what is needed from the server Data
No refresh page update, reducing user waiting time
For better customer experience, some server work can be transferred to the client to complete, saving network resources and improving user experience
No platform restrictions
Promote the separation of display and data
Disadvantages of AJAX asynchronous processing:There is a large amount of JS in the page, which brings difficulties to search enginesAJAX kills the Back and History functions, that is, it destroys the browser mechanism There is a cross-domain problemOnly utf-8 encoded data can be transmitted and received




1.AJAX implementation steps




window.open(URL,name,features,replace)

URL:
An optional string that declares the URL of the document to be displayed in the new window. If this parameter
is omitted or its value is an empty string, then the new window will not display any documents name:An optional string that is a A comma-separated list of characters, including numbers, letters, and underscores, This character declares the name of the new window. This name can be used as the value of the target attribute of the tags and

.
If this parameter specifies an existing window, then the open() method will no longer create a new window,
but only returns a reference to the specified window. In this case, features will be ignored
features: An optional string declaring standard browser features to be displayed in the new window. If this parameter is omitted,
the new window will have all standard features. In the window characteristics table, we describe the format of this string in detailreplace:

An optional Boolean value. Specifies whether a URL loaded into a window creates a new entry in the window's browsing history, or replaces the current entry in the browsing history. The following values ​​are supported: true - The URL replaces the current entry in the browsing history.
false - URL creates a new entry in the browsing history


send()send() is used to send data to a connected socket. If there is no error, the return value is the data sent. The total number,
Otherwise, return SOCKET_ERROR. [1] Send is also an English word.


responseText attribute:


The text version of the data returned by the server process
The DOM-compatible XML document object status server of the data returned by the server process The returned status code, such as: 404 = "File not found".
When you send an xmlhttp request to the ajax background program, the background program will process the request after receiving it. After the processing is completed, a string of data can be returned to Front desk,
This is responseText.
Generally in the background program C# it is Response.Write("string"). In php, echo is used...It is an output string
Because one character is output But sometimes what you get is an array, but you need to serialize it. Use the json technology in PHP to convert the array into a
string and output it to the front end, and the front end respText attribute can receive this string. Then use the json technology in JS to convert this stringConvert it again to an object recognized by JS for operation (the json data transmission type is basically recognized by any language and can be used for transmission and conversion in various languages)


Initialize the XMLHttpRequest object

  if (window.XMLHttpRequest) {// Mozilla, Safari, ...
var http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 5 ,6
var http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
Copy after login

XMLHttpRequest issues an HTTP request

http_request.open("GET|POST","test.php?GET方式传值",true);
          http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //仅POST请求时需要设置
         //用于向一个已经连接的socket发送数据
         //如果是POST传输方式要把值写在send()函数里
          http_request.send(向一个已连接的套接口发送数据);
      XMLHttpRequest取得响应数据并显示
       http_request.onreadystatechange=function(){
if(http_request.readyState==4  && http_request.status==200){
                    $("p").text(http_request.responseText)
         }
      }
Copy after login

Example:
//GET method
Parameter 1: Represents whether to send the request in get or post mode Parameter 2: To whom to send the request url Parameter 3: true represents an asynchronous request, false represents a synchronous request

http_request.open("GET","test.php?user_name="+username.val(),true);
http_request.send();
Copy after login

Send POST request

var username=$("input[name='user_name']");
Copy after login

Parameter 1: Represents whether to send the request in get or post mode Parameter 2 : Which url to send the request to Parameter 3: true represents an asynchronous request, false represents a synchronous request

http_request.open("POST","test.php",true);
http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
Copy after login

If it is a POST transmission method, the value must be written in the send() function

http_request.send({username:username});
Copy after login


4.JSON
Javascript Object Notation is a lightweight data exchange format
Every language knows JSON, so use it for various languages Data conversion
JSON supports multiple languages
Format
{key:value,key:value,.....} Object format
[{key:value,key:value,.. ...},{key:value,key:value,.....},...] Array format
PHP processing:
$json=json_encode($array) //Yes Variables are Json encoded
$array=json_decode($json) //Decode Json data and convert it into PHP variables
JavaScript processing:
eval('('+json+')') //Convert a certain A string is executed according to JS code
Example:

eval("x=10;y=20;document.write(x*y)")
document.write(eval("2+2"))
JSON.parse(json) //对传过来的json字符串进行解码,变成JS认识的对象
JSON.stringify(obj) //将JS中的值编译成json字符串
Copy after login


5. AJAX application in jQuery 1
. Don’t forget to write

$.ajax({
            //你要传的php文件的路径
            url:"test1.php",    ('服务器url地址')
            //以get方式传输拼接字符串
            data:"user_name="+$('input[name="user_name"]').val(),('名=值&名=值&.....',)
            //以什么方式传输
            type:'get',('post|get')
            //传输返回的数据类型
            dataType:'json',  ('xml|html|text|json|script')
            //展示 数据的方式
            success:function(res){
                $('h1').text('用户名为:'+res.user_name);
            },
                //错误信息
                error:function(xhr){
                },
              timeout:2000,
              async:true,
              cache:false
})
Copy after login

6. AJAX application in jQuery 2

$.get()
$.get('服务器url地址',"json格式或字符串格式",function(res){
        //处理返回的数据
}), "xml|html|json|text|script")
Copy after login

Example:

            //'服务器url地址',"json格式或字符串格式"
        $.get("test1.php",{user_name:$("input[name='user_name']").val()},function(data){
               //如果后台发过来的值跟这里的值相等让他执行下面代码
                if(data.status=='ok'){
                    alert("登陆成功");
                    location.href="http://www.wl.com";
                }else{
                    alert("登陆失败");
                }
        //"xml|html|json|text|script"类型
        },'json')
Copy after login


7. AJAX application in jQuery 3
serialize( ) The content of the sequence list table is a string, and the serialized data is used for Ajax requests

$.post()
$.post('服务器url地址',"json格式或字符串格式",function(res){
        //处理返回的数据
}), "xml|html|json|text|script")
Copy after login

Example:

//'服务器url地址',"json格式或字符串格式" 用post方式提交要用form表单包起来
        // 然后用serialize()来拿里面所有有值
        $.post("test1.php",$('form').serialize(),function(res){
            //如果后台发过来的值跟这里的值相等让他执行下面代码
            if(res.status=='ok'){
                alert("登陆成功");
                location.href="http://www.wl.com";
            }else{
                alert("登陆失败");
            }
            //"xml|html|json|text|script"类型
        },'json')
Copy after login

Receive and process output in php

try{
    $pdo=new PDO("mysql:host=127.0.0.1;port=3306;dbname=数据库名",'数据库账号','数据库密码');
    $pdo->exec("set names utf8");
    $sen=$pdo->query("select * from yh_admin where user_name='{$user_name}' limit 1");
    if($sen->rowCount()>0){
       // $arr=$sen->fetch(PDO::FETCH_ASSOC);
        //echo json_encode($arr);
        //echo 'yes';
       $arr['status']='ok';
    }else{
        echo 'no';
    }
    //切记用json数据类型传输
    echo json_encode($arr);
}catch (PDOException $e){
    echo $e->getMessage();
}
Copy after login

The above is the detailed content of Summary of knowledge points of jQuery's AJAX. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template