分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

ajax与fetch的用法

发布时间:2023-09-06 01:37责任编辑:沈小雨关键词:暂无标签
// 传统ajax用法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();// 传统ajax用法function req(url, data, callback) { ???var xhr = new XMLHttpRequest(); ???xhr.open(‘POST‘, url); ???xhr.onreadystatechange = function() { ???????if (xhr.readyState == 4 && xhr.status == 200) { ???????????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());// 替代ajax的fetchfetch(‘/users.json‘, { ???method: ‘POST‘, ???body: data, ???mode: ‘cors‘, ???redirect: ‘follow‘, ???headers: new Headers({ ???????‘Content-Type‘: ‘text/plain‘ ???})}).then(function(res) { ????console.log(res);}).then(function(res) { ???console.log(res);}).catch(function (err) { ???console.log(err);});// 使用async,await的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);

  

ajax与fetch的用法

原文地址:https://www.cnblogs.com/huangtonghui/p/8311476.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved