简体   繁体   English

使用 ES6 的 jQuery ajaxSetup

[英]jQuery ajaxSetup with ES6

How do I replicate the behavior of jQuery's ajaxSetup with vanilla JS (ES6 in this case)?如何使用 vanilla JS(在本例中为 ES6)复制 jQuery ajaxSetup 的行为?

Here's what I'm trying to achieve.这就是我想要实现的目标。 Currently I have in my app.js:目前我在我的 app.js 中有:

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

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.因此,当我在任何其他文件中执行任何 ajax 请求时,_token 将包含在我提供的数据 json 对象中,这样我就不必在每次调用时都指定 _token 以确保它永远不会错过。

How to do this with ES6 only?如何仅使用 ES6 做到这一点?

Wrap the Fetch api and store your base data and merge that with whatever you send with it.包装 Fetch api 并存储您的基本数据并将其与您发送的任何内容合并。

 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) })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM