Ajax-related questions

Introduction to AJAX

The full name of AJAX is Asynchronous JavaScript And XML, which is asynchronous JS and XML.
AJAX can send an asynchronous request to the server in the browser, the biggest advantage: get data without refreshing.
AJAX is not a new programming language, but a new way of combining existing standards.
AJAX is not a new language, but a programming model that integrates multiple network technologies such as HTTP asynchronous communication, JS, XML, and JSON.

AJAX= JS+XML+JSON+HTTP communication, the essence is to communicate in an asynchronous manner based on the HTTP protocol.

XML:

XML Extensible Markup Language.
XML was designed to transmit and store data.
XML is similar to HTML, the difference is that there are predefined tags in HTML, but there are no predefined tags in XML.
All are custom tags used to represent some data.
比如说我有一个学生数据: 
name = "孙悟空" ; age = 18 ; gender = "男" ;
用 XML 表示: 
<student> 
  <name>孙悟空</name> 
  <age>18</age> 
  <gender>男</gender> 
</student>
It has now been superseded by JSON.
用 JSON 表示: {"name":"孙悟空","age":18,"gender":"男"}

Advantages and disadvantages of ajax

Ajax is also called non-refresh technology such as maps and partial loading

①Advantages:

1. It is possible to communicate with the server without refreshing the page.

2. It can make full use of the idle processing capacity of the client and reduce the burden on the server and network transmission. (For example, the following data will be displayed only when you scroll to the bottom, and the dialog interface will be displayed only when some modules are clicked, and the corresponding data will be displayed.)

3. Separating the interface and application in the web can also be said to be the separation of data and presentation

②Disadvantages:

1. There is no browsing history, and you cannot go back. AJAX kills the Back and History functions, which is the destruction of the browser mechanism.

2. AJAX security problem, there is a cross-domain problem, and it cannot be accessed across pages

3. SEO is not very friendly, and the interface data is dynamically obtained through ajax requests

ajax handles network requests

The ajax module includes the following four steps when processing network requests

        ① Create an xhr object through the XMLHttpRequest class

        ② Add attributes and callback methods to the xhr object

        ③ Let the xhr object execute the open() method, indicating that the request is sent somewhere

        // Specifies the type of request, the URL, and whether to process the request asynchronously. xhr.open('GET',url,true);

        ④ Let the xhr object execute the send() method to send a request.

Supplement: Ajax can issue synchronous requests or asynchronous requests. But in most cases it refers to asynchronous requests, because synchronous Ajax requests have a 'blocking effect' on the browser.

Send GET, POST request

<script>
    /**
     *需求: 点击 button 按钮发送 GET请求,将服务端返回的响应体结果返回在 div 中,页面不刷新
     */
    // 获取 button 元素
    const btn  = document.getElementsByTagName('button')[0];
    const result = document.getElementById('result');
    btn.onclick = function() {
        // 1. 创建对象
        const xhr = new XMLHttpRequest();
        // 2. 初始化 设置请求方法和 url /server 是设置路径
        // 给 url 传递参数 用?分割加参数与值 进行传参,参数之间用&分割
        xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200&c=300');
        // 3. 发送
        xhr.send();
        // 4. 事件绑定,处理服务器返回的结果
        // on when··· 当····时
        // readystate 是 xhr 对象中的属性,表示状态
        // 其状态值分别为 0(未初始化) 1(open方法已调用完毕) 2(表示send方法已调用完毕) 3(服务端已返回部分结果) 4(服务端返回全部结果)
        // change 改变
        xhr.onreadystatechange = function () {
            // 判断 (服务端返回了全部结果)
            if(xhr.readyState === 4){
                // 判断响应状态码 200 404 403 401 500
                // 2xx 都表示成功
                if(xhr.status >= 200 && xhr.status < 300){
                   /**
                    // 处理结果 行 头 空行 体
                    // 1.响应行
                    console.log(xhr.status); // 状态码
                    console.log(xhr.statusText); // 状态字符串
                    console.log(xhr.getAllResponseHeaders()); // 所有的响应头
                    console.log(xhr.response); // 响应体
                    */

                   //设置result文本
                   result.innerHTML = xhr.response;
                }else {

                }
            }
        }
    }

</script>
<script>
    /**
     * 当鼠标放在 div 上面时,发送POST请求,将响应体结果在div当中呈现
     */
    // 获取元素对象
    const result = document.getElementById('result');
    //绑定事件
    result.addEventListener('mouseover',function () {
        // 1. 创建对象
        const xhr = new XMLHttpRequest();
        // 2. 初始化 设置类型与 url
        xhr.open('POST','http://127.0.0.1:8000/server');

        //设置请求头
        // 第一个参数: 头名 设置请求体内容的类型
        // 第二个参数:头值 参数查询字符串的类型 (写法固定)
        // 加预定义的响应头
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        // 如果要设置自定义的响应头,需要后端人员在.js文件中设置
        xhr.setRequestHeader('name','atguigu');


        // 3. 发送
        // post请求 参数的设置是在 send()方法中
        // xhr.send('a=100&b=200&c=300');
        xhr.send('a:100&b:200&c:300');

        // 4. 事件绑定
        xhr.onreadystatechange = function () {
            // 判断
            if(xhr.readyState === 4){
                if(xhr.status >= 200 && xhr.status < 300){
                    // 处理服务器端返回的结果
                    result.innerHTML = xhr.response;
                }
            }
        }
    })
</script>

How many ajax request methods? Their pros and cons?

Commonly used post, get, delete. Copy, head, link, etc. are not commonly used.

code difference

 1: get passes parameters through url
 2: post sets the request header to specify the request data type

difference in use

 1: post is safer than get
 (because the post parameters are in the request body. The get parameters are on the url)
 2: the transmission speed of get is faster than that of post, which is determined by passing parameters.
 (Post passes parameters through the request body, and the background receives them through data streams. The speed is slightly slower. Get can be directly obtained by passing parameters through url) 3: There is no limit to the
 large theory of post transfer files. The size of get transfer files is about 7-8k ie4k or so
 4: get get data post upload data
 (there are a lot of uploaded data and the uploaded data is important data. So post is the best choice no matter in terms of security or data magnitude)

cross-domain issues

What causes cross-domain?

The same-origin policy restricts different origins to cause cross-domain. Any one of the following situations is different, and it is a different source.

http://www.baidu.com/8080/index.html

http:// agreement is different
www different subdomains
baidu.com Primary domain name is different
8080 different port numbers
www.baidu.com ip address and url are different

1 jsonp can only solve get cross-domain (the most asked)

principle

Some tags on web pages are inherently capable of cross-domain, such as: img link iframe script. JSONP uses the cross-domain capabilities of script tags to send requests.

Create a script tag dynamically. Using the src attribute of the script tag is not restricted by the same-origin policy. Because all src attributes and href attributes are not restricted by the same-origin policy. Third-party server data content may be requested.

step

  1. to create a script tag
  2. The src attribute of the script sets the interface address
  3. Interface parameters must have a custom function name, otherwise the background cannot return data.
  4. Receive data returned by the background by defining the function name
//去创建一个script标签
var  script = document.createElement("script");

//script的src属性设置接口地址 并带一个callback回调函数名称
script.src = "http://127.0.0.1:8888/index.php?callback=jsonpCallback";

//插入到页面
document.head.appendChild(script);

//必须通过定义函数名去接收后台返回数据
function jsonpCallback(data){
    //注意  jsonp返回的数据是json对象可以直接使用
    //ajax  取得数据是json字符串需要转换成json对象才可以使用
    console.log(data)
}

CORS: Cross-Origin Resource Sharing

  • principle:

After setting the Access-Control-Allow-Origin HTTP response header on the server side, the browser will allow cross-domain requests

  • limit

The browser needs to support HTML5, can support POST, PUT and other methods compatible with ie9 or above

需要后台设置
Access-Control-Allow-Origin: *              //允许所有域名访问,或者
Access-Control-Allow-Origin: http://a.com   //只允许所有域名访问

set document.domain

  • principle:

For pages under the same main domain name and different subdomain names , you can set document.domain to make them the same domain

  • limit:

This solution is only applicable to cross-domain communication scenarios where the main domain is the same and subdomains are different. As shown in the figure below, the two pages http://a.qq.com/a.html and http://b.qq.com/b.html that do not comply with the same-origin policy have the same main domain as qq.com . a.html nests b.html, and then set document.domain as the main domain qq.com through js, then the two pages satisfy the same-origin policy, thus realizing cross-domain communication.

Document.domain+iframe program code example:

1. Add document.domain = "qq.com" to both http://a.qq.com/a.html and http:/b.qq.com/b.html;
2. Through a The .html file creates an iframe to control the window of the iframe for interaction.

<!-- A页面 http://a.qq.com/a.html -->
<iframe id="iframe" src="http://b.qq.com/b.html"></iframe>
<script>
    document.domain = "qq.com";
    var windowB = document.getElementById("iframe").contentWindow;
    alert("B页面的user变量:" + windowB.user);
</script>
<!-- B页面 http://b.qq.com/b.html -->
<script>
    document.domain = "qq.com";
    var user = "saramliu";
</script>

Advantages of document.domain+iframe solution:

  • The implementation logic is simple and no additional transition pages are required

Disadvantages of document.domain+iframe scheme:

  • Only applicable to the cross-domain scenario of front-end communication with the same main domain and different sub domains

Supplement: iframe.contentWindow property:


Regarding the definition and usage of contentWindow and contentDocument

The contentDocument attribute can return the document in the iframe as an HTML object, and the returned object can be processed by all standard DOM methods.
grammar:

frameObject.contentWindow, or iframeObject.contentWindow (not the jquery object)

When nesting pages with iframe, if the parent page wants to get the content in the child page, you can use contentWindow or contentDocument, the difference is as follows:
  1. contentWindow is a read-only attribute, which returns the window object of the specified iframe. Although it is not part of the standard, it is supported by all major browsers.

      2. contentDocument is supported by Firefox, IE6 and IE7 do not support it, and IE8 starts to support it. You need to access document.frames['J_mainframe'].document in this way.

What are the common status codes of HTTP?

 

1xx information status code Information

请求已经被服务器接收,继续处理

2xx success status code Success

200 (成功) 服务器已成功处理了请求。 通常正常访问返回。

3xx redirect status code Redirection

3xx (redirect) indicates that further action is required to complete the request.

301(moved permannently) 表示永久重定向,表示请求的资源分配了新的url,以后使用新的url

302	Found	临时移动。与301类似。但资源只是临时被移动。客户端应继续使用原有URl

304	Not Modified	未修改。所请求的资源未修改,服务器返回此状态码时,不会返回任何资源。客户端通常会缓存访问过的资源,通过提供一个头信息指出客户端希望只返回在指定日期之后修改的资源

305	Use Proxy	使用代理。所请求的资源必须通过代理访问

306	Unused	已经被废弃的HTTP状态码

307	Temporary Redirect	临时重定向。与302类似。使用GET请求重定向

 Status code starting with 4

4xx client error, the request contained syntax errors or could not be completed

 常用 400 (错误请求 Bad Request) 客户端请求的语法错误,服务器无法理解

 常用 403 (禁止 Forbidden) 服务器理解请求客户端的请求,但是拒绝执行此请求

 常用 404 (未找到 Not Found) 服务器无法根据客户端的请求找到资源(网页)。通过此代码,网站设计人员可设置"您所请求的资源无法找到"的个性页面


401  未授权 Unauthorized 	请求要求用户的身份认证

405	Method Not Allowed	客户端请求中的方法被禁止

407	Proxy Authentication Required	请求要求代理的身份认证,与401类似,但请求者应当使用代理进行授权

408	Request Time-out	服务器等待客户端发送的请求时间过长,超时

410	Gone 客户端请求的资源已经不存在。410不同于404,如果资源以前有现在被永久删除了可使用410代码,网站设计人员可通过301代码指定资源的新位置

Status code starting with 5

 5xx server error, the server encountered an error while processing the request

500 (服务器内部错误) 服务器遇到错误,无法完成请求。

501 (尚未实施) 服务器不具备完成请求的功能。 例如,服务器无法识别请求方法时可能会返回此代码。

502 (错误网关) 服务器作为网关或代理,从上游服务器收到无效响应。

503 (服务不可用) 服务器目前无法使用(由于超载或停机维护)。 通常,这只是暂时状态。

504 (网关超时) 服务器作为网关或代理,但是没有及时从上游服务器收到请求。

505 (HTTP 版本不受支持) 服务器不支持请求中所用的 HTTP 协议版本,无法完成处理。

ajax important and commonly used parameters

Important parameters of ajax

$.ajax({
    url:  "请求路径",
    type: "post",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({
        id:'666',
        name:'莎莎酱'
    }),  //将json对象转为json字符串
    dataType: "json", //表示接受的数据为json类型
    success: function (data) {
        // 请求成功后执行的代码
        if (data.success) {
            
        } else {    
            
        }
    },
    error: function(){  
    
    }

Common parameters:

url:

Requires a parameter of String type, (the default is the address of the current page) to send the request address.
This is where the request is sent to the corresponding background for processing, and the background distinguishes different requests according to this url.

type:

A parameter of String type is required, and the request method (post or get) defaults to get.
Note that other http request methods, such as put and delete can also be used, but only some browsers support them.

post:

The browser sends each form field element and its data to the Web server as the entity content of the HTTP message, and the amount of data is much larger than that transmitted by GET, which is safe.

get:

The get method can transmit simple data, which has a size limit. The data is appended to the url and sent (transmitted by the header of http), the url can be cached by the client, and the customer data is obtained from the browser history, which is not safe.

async:

It is required to be a Boolean type parameter, the default setting is true, and all requests are asynchronous requests.
Set this option to false if you need to send synchronous requests.
Note that a synchronous request will lock the browser, and other operations of the user must wait for the request to be completed before they can be executed.

data:

The data sent to the server requires parameters of type Object or String.
If it is not already a string, it will be automatically converted to string format. The get request will be appended to the url.
To prevent this automatic conversion, see the processData option.
The object must be in key/value format. If it is an array, JQuery will automatically correspond to the same name for different values.

// 对象必须为key/value格式。例如:
{
    foo1:"bar1",
    foo2:"bar2"
}
=>&foo1=bar1&foo2=bar2

// 如果是数组,JQuery将自动为不同值对应同一个名称。例如:
{
    foo:["bar1","bar2"]
} 
=> &foo=bar1&foo=bar2

dataType:

Requires a parameter of type String, the expected data type returned by the server.
If not specified, JQuery will automatically return responseXML or responseText according to the mime information of the http package, and pass it as a callback function parameter.

常用类型:
xml:返回XML文档,可用JQuery处理。
html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。
json:返回JSON数据。如果指定为json类型,则会把获取到的数据作为一个JavaScript对象来解析,并且把构建好的对象作为结果返回。
text:返回纯文本字符串。

success:

Requires a parameter of Function type, the callback function invoked after the request succeeds, with two parameters.
(1) The data returned by the server and processed according to the dataType parameter.
(2) A character string describing the status.

1  function(data, textStatus){
2      //data就是后台处理之后,返回的一个javascript对象,里面包含前台需要的各种信息,需要什么塞什么,data可能是xmlDoc、jsonObj、html、text等等
3      this;  //调用本次ajax请求时传递的options参数
4 }

error:

Requires a parameter of type Function, the function to be called when the request fails. This function has 3 parameters, namely XMLHttpRequest object, error message, and captured error object (optional).

1  function(XMLHttpRequest, textStatus, errorThrown){
2      //通常情况下textStatus和errorThrown只有其中一个包含信息
3      this;   //调用本次ajax请求时传递的options参数
4 }

contentType:

It is required to be a parameter of String type. When sending information to the server, the content encoding type defaults to "application/x-www-form-urlencoded". This default is suitable for most applications.
multipart/form-data: Sometimes this is also used for uploading and downloading.
contentType: "application/json; charset=utf-8" This may also be often used.

timeout:

It is required to be a parameter of the Number type, and set the request timeout (in milliseconds). This setting will override the global setting of the $.ajaxSetup() method.

synchronous and asynchronous

After talking about processes and threads, let's talk about synchronous and asynchronous.
Everyone knows that js is a single-threaded mechanism. It is divided into two working modes, synchronous mode and asynchronous mode.
Synchronization : When a function call is issued, the call will not return or continue to perform subsequent operations until the result is obtained. To put it simply, synchronization means that one thing must be done one by one, and the next thing can only be done after the previous one is finished.
Asynchronous : As opposed to asynchronous, when it sends a function call, it can continue to perform follow-up operations before getting the result, and notify the caller after the call is completed. In layman's terms, this thing is being done and not finished, but you can go to the next thing, and you will be notified when this thing is done .

Guess you like

Origin blog.csdn.net/csdssdn/article/details/126136108