首页 > 解决方案 > 使用 AJAX DELETE 请求清除数组

问题描述

我正在尝试从客户端向服务器发送 AJAX DELETE 请求以清空数组模块。

这是我的客户端请求:

function clearHistory(){
  $.ajax({
    type: 'DELETE',
    url: '/calc',
    data: { method: 'delete'}
  }).then(function(response){
    console.log(response);
  })
}

这是服务器端:

app.delete('/calc', (req,res)=>{
    history= [];
    res.sendStatus(201);
})

同样在服务器端,我正在导入历史数组:

let history = require('./modules/history.js');

最后,我的 history.js 模块中存储了一个历史数组:

const history = [];

module.exports= history;

数组没有像我想要的那样清空。我认为我的问题在于客户端请求中的数据对象,但我对 AJAX 请求的了解不足,无法解决此问题。

任何帮助,将不胜感激。

标签: javascriptajaxmodule

解决方案


尝试history用对象包装数组:

历史.js

const history = [];
module.exports = { list: history };

接着

const history = require('./modules/history.js');
app.delete('/calc', (req,res) =>{
    history.list = [];
    res.sendStatus(201);
})

推荐阅读