带有ES6的jQuery ajaxSetup [英] jQuery ajaxSetup with ES6

查看:138
本文介绍了带有ES6的jQuery ajaxSetup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用香草JS(在这种情况下为ES6)复制jQuery的ajaxSetup的行为?

How do I replicate the behavior of jQuery's ajaxSetup with vanilla JS (ES6 in this case)?

这就是我要实现的目标.目前我在app.js中:

Here's what I'm trying to achieve. Currently I have in my app.js:

$(document).ready(()=>{
    $.ajaxSetup({
        data: {'_token': $('meta[name="csrf-token"]').attr('content')}
    });     
 })

因此,当我在任何其他文件中执行任何ajax请求时,_token将包含在我提供的数据json对象中,这样,我不必在每次调用时都指定_token来确保它不会被遗漏.

So when I perform any ajax request in any other file, _token will be include to the data json object that I'm providing, that way I don't have to specify _token on every call making sure that it's never missed.

如何仅使用ES6做到这一点?

How to do this with ES6 only?

推荐答案

包装Fetch api并存储您的基本数据,并将其与您随其发送的内容合并.

Wrap the Fetch api and store your base data and merge that with whatever you send with it.

class MyFetch {
  constructor(data) {
    this.data = data
  }

  post(url, data) {
    let requestData = {
      ...this.data,
      ...data
    }
    return fetch(url, {
      method: 'POST',
      body: JSON.stringify(requestData)
    })
  }
}

let myFetch = new MyFetch({
  _token: 'helloworld'
})

myFetch.post('https://httpbin.org/post',{moreData:'more'})
  .then((res) => res.json())
  .then(json => {
    console.log('Data sent:', json.data)
  })

这篇关于带有ES6的jQuery ajaxSetup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆