jq中使用promise封装ajax

let ajax=function(url, param, type = ‘GET‘){
    const promise = new Promise(function(resolve, reject){
        $.ajax({
            type: type,
            url: url,
            data: param,
            dataType: ‘json‘,
            success(res) {
                resolve(res)
            },
            error(res) {
                reject(‘响应错误‘)
                // reject(res.statusText)
            }
        })
    })
    return promise
}

// 使用示例
ajax(‘http://wh.xhd.cn/api/content/list.jspx‘,{channelIds: 1}).then(res=>{
    console.log(res)
})

原文地址:https://www.cnblogs.com/nanacln/p/11174840.html

时间: 2024-08-30 16:53:54

jq中使用promise封装ajax的相关文章

ES6之Promise封装ajax()

什么是异步? 同步:一定要等任务执行完了,得到结果,才执行下一个任务. 异步:不等任务执行完,直接执行下一个任务. 为什么要用promise? Promise的出现主要是解决地狱回调的问题,比如你需要结果需要请求很多个接口,这些接口的参数需要另外那个的接口返回的数据作为依赖,这样就需要我们一层嵌套一层,但是有了Promise 我们就无需嵌套 Promise的本质就是分离了异步数据获取和业务逻辑 所有代码 Promise/A+规范 $.Ajax()中的promise 如果不使用promise,$.

使用promise封装Ajax

一.封装Ajax 1 <script> 2 var ajax = new Promise((resolve, reject) => { 3 var xhr = new XMLHttpRequest(); 4 xhr.open('get', './test1.txt', true); 5 xhr.send(); 6 xhr.onreadystatechange = function() { 7 if (xhr.status == 200 && xhr.readyState

jq中ajax的使用

jq中ajax必须在服务器环境下使用 $.ajax({ url:"json.json", //请求的url地址 dataType:"json", //返回格式为json type:"GET", //请求方式 beforeSend:function(){ $('#div3').html('加载中...') }, success:function(data,status){//第一个参数包含获取的内容,第二个参数为执行的状态 var tt="

JavaScript封装Ajax工具函数及jQuery中的ajax

封装ajax工具函数 /** * ITCAST WEB * Created by zhousg on 2016/5/24. */ /* * 1. 请求的类型 type get post * 2. 请求地址 url * 3. 是异步的还是同步的 async false true * 4. 请求内容的格式 contentType * 5. 传输的数据 data json对象 * * 6.响应成功处理函数 success function * 7.响应失败的处理函数 error function *

jq中的ajax合集总结

参考原文 jq中关于ajax的方法很多 重点关注打红点的几个 1.首先说说$,ajax(), 其实后面要讲到的$.get(),$.post()等等都是基于$.ajax()的,都可以改写成$.ajax()的形式, 示例: html: 1 <html> 2 <head> 3 <meta charset="UTF-8"> 4 <title>$.ajax()方法</title> 5 <script src="../js

简单的基于promise的ajax封装

基于promise的ajax封装 1 //调用方式: 2 /* 3 ajaxPrmomise({ 4 url:, 5 method:, 6 headers:{} 7 }).then(res=>{}) 8 */ 9 10 ;(function(window){ 11 //设置默认的参数配置项 12 let _default = { 13 url:'', 14 baseURL:'', 15 method:'GET', 16 params:null, //get请求基于问号传参方式传递给服务器的内容

jq中的ajax传参

    一.   jq中的Ajax传参有两种           1.通过url地址来传参    2.通过data来传递参数 1. url来传递参数 function GetQuery(id) { if (id ==1||id==7) { var name = "语文"; $.ajax({ url:"../ajaxHandler/ChartsHandler.ashx?id="+id+"&name="+name +"",

仿jq封装ajax

/** * 封装ajax */ function ajax () { var ajaxData = { type: arguments[0].type || 'GET', url: arguments[0].url || '', async: arguments[0].async || 'true', data: arguments[0].data || null, dataType: arguments[0].dataType || 'text', contentType: arguments

深入理解jQuery、Angular、node中的Promise

最初遇到Promise是在jQuery中,在jQuery1.5版本中引入了Deferred Object,这个异步队列模块用于实现异步任务和回调函数的解耦.为ajax模块.队列模块.ready事件提供基础功能.在用jQuery操作DOM的时候对Promise的使用欲不够强烈,最近学习node和Angular,需要用js写业务逻辑和数据操作代码的时候这种场景需求就出来了.一般来说事件适合在交互场景中运用,因为用户的行为本来就是分散的,而promise这样的流程控制适合在后台逻辑中处理业务. //j