Home > php教程 > PHP开发 > ajax design plan

ajax design plan

高洛峰
Release: 2016-11-30 14:32:12
Original
1332 people have browsed it

Report, I want to speak! XP has been eliminated by history, IE6 says goodbye, I’m so damn happy, I won’t be compatible with IE6 from now on, hahahahahahahahahahahahahahahahahahahahahahahahahaha

Report, I want to speak! Why wasn't this sb IE killed earlier? I heard that IE compatibility was required when I was looking for a job, so I immediately softened up, alas, alas, alas, alas,

report, I want to speak! Jquery is too rich. I only use a few functions. Damn, it is not cost -effective, ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ah ... oh, good, words belong to home. Regarding the idea of ​​sorting out the ajax design plan, the reasons are as follows:

Thinking from the perspective of rational utilization of resources and website optimization, it is not cost-effective to reference a framework every time just for those few functions

I read the ajax design plan of w3c , including the specifications of level1 and level2, there is a feeling of sudden enlightenment

A friend encountered the cross-domain solution of ajax, and was tangled in his heart, which made him feel uncomfortable

The bottom layer of his own framework also needs to use the foundation of ajax Function, (get post request, not used for level2 upload yet)

The most important thing is that I was very vague about this concept before, so I started to sort out the design plan for ajax

Introduce some concepts:

Browse The same origin policy of the browser: the most basic security function of the browser. The same origin means that the domain name, protocol and port are the same (so the interface deployment ports I wrote are 1122 and 2211 respectively, which means they are not of the same origin and are cross-domain)

ajax : It is a technical solution that relies on CSS/HTML/Javascript. The core dependency is the XMLHttpRequest object provided by the browser. This object allows the browser to issue HTTP requests and receive HTTP responses.

XMLHttpRequest Level 1 mainly has the following shortcomings:

Restricted by the same origin policy, cross-domain requests cannot be sent;


cannot send binary files (such as pictures, videos, audios, etc.), and can only send plain text data ;

During the process of sending and obtaining data, progress information cannot be obtained in real time, and you can only judge whether it is completed;

XMLHttpRequest Level 2 has added the following functions:

You can send cross-domain requests, which are allowed on the server side


Supports sending and receiving binary data;

Added formData object to support sending form data;

You can get progress information when sending and getting data;

You can set the timeout of the request;

XMLHttpRequest The compatibility is as follows:

nginx: It is a high-performance HTTP and reverse proxy server

ajax design planIIS: a server developed by Microsoft, which comes with the window system

Start preparation as follows:

Pure front-end code

nginx reverse proxy server (for front-end and back-end separation)

Backend 2 sockets (port: 1122, port: 2211) PS: One copy must support cross-domain requests

IIS server (deployment backend interface)

chrome plug-in postman (Interface test)

IE, chrome, firefox, Opera, safari, edge 6 major browsers, do compatibility testing

XMLHttpRequest sending request steps:

Instantiate the XMLHttpRequest object (IE8-9 is the ActiveXObject encapsulated by Microsoft (' Microsoft. Call the send method of the instance to send an http/https request

server callback, the client receives it, and does response processing

The key points of the code are as follows:

//创建xhr对象
    var xhr = createXhrObject();

    //针对某些特定版本的mozillar浏览器的BUG进行修正
    xhr.overrideMimeType?(xhr.overrideMimeType("text/javascript")):(null);

    //针对IE8的xhr做处理 PS:ie8下的xhr无xhr.onload事件,所以这里做判断
    xhr.onload===undefined?(xhr.xhr_ie8=true):(xhr.xhr_ie8=false);

    //参数处理(get和post),包括xhr.open     get:拼接好url再open   post:先open,再设置其他参数
    ajaxSetting.data === ""?(null):(xhr = dealWithParam(ajaxSetting,this,xhr));

    //设置超时时间(只有异步请求才有超时时间)
    ajaxParam.async?(xhr.timeout = ajaxSetting.time):(null);

    //设置http协议的头部
    each(ajaxSetting.requestHeader,function(item,index){xhr.setRequestHeader(index,item)});

    //判断并设置跨域头部信息
    (ajaxSetting.crossDomain)?(xhr = addCoreHeader(xhr,ajaxSetting)):(null);

    //onload事件(IE8下没有该事件)
    xhr.onload = function(e) {
        if(this.status == 200||this.status == 304){
            ajaxSetting.dataType.toUpperCase() == "JSON"?(ajaxSetting.success(JSON.parse(xhr.responseText))):(ajaxSetting.success(xhr.responseText));
        }else{
            /*
             *  这边为了兼容IE8、9的问题,以及请求完成而造成的其他错误,比如404等
             *   如果跨域请求在IE8、9下跨域失败不走onerror方法
             *       其他支持了Level 2 的版本 直接走onerror
             * */
            ajaxSetting.error(e.currentTarget.status, e.currentTarget.statusText);
        }
    };

    //xmlhttprequest每次变化一个状态所监控的事件(可拓展)
    xhr.onreadystatechange = function(){
        switch(xhr.readyState){
            case 1://打开
                //do something
                break;
            case 2://获取header
                //do something
                break;
            case 3://请求
                //do something
                break;
            case 4://完成
                //在ie8下面,无xhr的onload事件,只能放在此处处理回调结果
                xhr.xhr_ie8?((xhr.status == 200 || xhr.status == 304)?(ajaxSetting.dataType.toUpperCase() == "JSON"?(ajaxSetting.success(JSON.parse(xhr.responseText))):(ajaxSetting.success(xhr.responseText))):(null)):(null);
                break;
        };
    };

    //ontimeout超时事件
    xhr.ontimeout = function(e){
        ajaxSetting.timeout(999,e?(e.type):("timeout"));   //IE8 没有e参数
        xhr.abort();  //关闭请求
    };

    //错误事件,直接ajax失败,而不走onload事件
    xhr.onerror = function(e){
        ajaxSetting.error();
    };

    xhr.send((function(result){this.postParam == undefined?(result =null):(result=this.postParam);return result;})(this.postParam));
Copy after login

The test code is as follows:

Front-end same-origin test code

ajax.post("/api/ajax1/ajaxT1/",{"name":"测试异步post请求","age":"success"},function(data){alert(data)});  //该接口在1122上
Copy after login

Front-end cross-domain test code

ajax.post_cross("http://192.168.0.3:2211/api/weixin/ajaxT2/",{"name":"测试跨域post请求","age":"success"},function(data){alert(data)});
Copy after login

Back-end cross-domain interface code

/// <summary>
   /// 测试跨域请求
   /// </summary>
   /// <param name="module"></param>
   /// <returns></returns>
   [Route("ajaxT2")]
   public String kuaAjaxT2([FromBody]TModule module)
   {
       String result = "跨域post传输成功:"+module.name+"-"+module.age;
       return result;
   }
Copy after login

Back-end same-origin interface code

/// <summary>
/// 测试ajax同源请求
/// </summary>
/// <param qwer="code"></param>
/// <returns>result</returns>
[Route("ajaxT2")]
public String GetkuaAjaxT1(string name,string age)
{
    String result = "1J跨域成功:" + name + "-" + age;
    return result;
}
Copy after login

The following are tests on various browsers Results (only same-origin post requests and cross-domain post requests are provided):

Original test:

chrome


IE8-9

ajax design planIE10+

ajax design planfirefox

ajax design plan

opera

ajax design plan

safari

ajax design plan

edge

ajax design plan

Cross-domain testing:

chrome

ajax design plan

IE8-9

ajax design plan

ajax design plan

IE10+

ajax design plan

firefox

ajax design plan

opera

ajax design plan

safari

ajax design plan

edge

ajax design plan

The specific code has been encapsulated into a js library for everyone to develop and customize according to project needs, but I have encapsulated some common requests:

Asynchronous get request -- ajax.get

Asynchronous post request--ajax.post

synchronous get request--ajax.get_sync

synchronous post request--ajax.post_sync

cross-domain get request--ajax.get_cross

cross-domain post request -- ajax.post_cross

Common configuration request -- ajax.common

The code and test page have been uploaded to github. If you want to test the backend interface, just write one yourself. The backend code will not be uploaded. Key compression It’s all over, only 4K!


Related labels:
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template