The use of Ajax and fetch

Source: Internet
Author: User

Traditional Ajax usage var xhr = new XMLHttpRequest (); xhr.responsetype = ' json '; xhr.timeout = 2000;console.log (xhr.readystate);//    0xhr.open (' GET ', url); Console.log (xhr.readystate);//1xhr.onloadstart = function (e) {xhr.abort (); Console.log (e);}; xhr.onprogress = function (e) {console.log (xhr.readystate);//3 Console.log (e);};    Xhr.onload = function (res) {Console.log (res); Console.log (xhr.readystate);//4};xhr.onerror = function (err) {Console.log (err);}; Xhr.ontimeout = function (e) {console.log (e);}; Xhr.onabort = function (e) {console.log (e);}; xhr.onloaded = function (e) {console.log (e);};    Xhr.send ()///Traditional Ajax usage function req (URL, data, callback) {var xhr = new XMLHttpRequest ();    Xhr.open (' POST ', url); Xhr.onreadystatechange = function () {if (xhr.readystate = = 4 && Xhr.status = =) {var res =            Json.parse (Request.responsetext);        Callback (RES);    }    }; Post Xhr.setrequestheader (' Content-type ', ' application/x-www-fOrm-urlencoded ');    Xhr.send (data);    Get Xhr.setrequestheader ("Content-type", "text/xml;charset=utf-8"); Xhr.send (null);} Req (URL, data, callback ());//Alternate Ajax Fetchfetch ('/users.json ', {method: ' POST ', body:data, mode: ' Cors ', red Irect: ' Follow ', headers:new headers ({' Content-type ': ' Text/plain '})}). Then (function (res) {Console.lo g (res);}). Then (function (res) {Console.log (res);}). catch (function (err) {Console.log (err);});        /Use Async,await's Fetchasync function req (URL, data) {try {Let response = await fetch (URL, data);        Let data = await Response.json ();    Console.log (data);    } catch (Err) {Console.log (err); }}req (' https://www.baidu.com ', data);

  

The use of Ajax and fetch

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.