将删除请求匹配到json对象

时间:2018-12-07 00:35:08

标签: javascript jquery json ajax express

当使用AJAX删除功能以某种形式显示对象值时,我正在尝试从json文件中删除json对象。我正在使用express为json文件生成路由,如下所示:

app.get('/users', (req, res) => {
    var userData = json;
    
    res.send(userData);
        
        }), 
        
app.delete('/users/delete/:id', (req, res) => {
    var key = req.params.id;
    var deletedData = json;
    
    deletedData.splice(key, 1);
    res.send(deletedData);

});

      $(document).on('click', '#delete', function () {
             $.ajax({
                    type: "DELETE"
                    , url: "users/delete/"+data[key]  
                    , datatype: "datatype"
                    , success: function (data) {
                        console.log(data);
       
                        }   
                });
            });

我知道我没有声明data [key],这只是我想做的事情的上下文。我的问题是尝试选择特定的json对象,而不只是选择第一个对象,即我现在拥有的“ users / delete / 0',有人知道如何做到这一点吗?

编辑

我试图获取特定于该对象的“ users / delete /:id”,该对象显示在html的表单中

                <div class="col-md-5 col-sm-12">
                    <div id="full_details">
                        <ul class="details">
                            <h2>Contact Details</h2> <img src="" alt="Avatar" id="avatar">
                            
                            
                            <li>Name
                                <input type="text" id="name" class="form-control mr-sm-2" disabled>
                            </li>
                            <li>Address
                                <input type="text" id="address" class="form-control mr-sm-2" disabled>
                            </li>
                            <li>Contact Number
                                <input type="text" id="phone" class="form-control mr-sm-2" disabled>
                            </li>
                            <li>Email
                                <input type="text" id="email" class="form-control mr-sm-2" disabled>
                            </li>
                            <li>Postcode
                                <input type="text" id="postcode" class="form-control mr-sm-2" disabled>
                            </li>
                            <li>City
                                <input type="text" id="city" class="form-control mr-sm-2"disabled>
                            </li>
                            <li>Country
                                <input type="text" id="country" class="form-control mr-sm-2" disabled>
                            </li>
                            <div class="row">
                                <div class="col-md-6">
                                    <div id="editbutton">
                                        <p class="btn btn-primary">Edit Details</p>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div id="savebutton">
                                        <p class="btn btn-danger">Save Details</p>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div id="delete">
                                        <p class="btn btn-danger">delete</p>
                                    </div>
                                </div>
                            </div>
                        </ul>
                    </div>
                </div>

2 个答案:

答案 0 :(得分:0)

需要在要执行操作的位置提供JSON数据。如果您尚未在代码段之外执行此操作,则需要将您的JSON放入Express删除路由所在的文件中。

在当前的delete路由中,.splice方法仅适用于字符串和数组(除非您在Object.prototype上定义了方法)。

如果您的JSON数据是一个对象,那么这是delete路由的示例:

let userJSON = require('./users.json');

app.delete('/users/delete/:id', (req, res) => {
    let key = req.params.id;
    if( delete userJSON.key ){
        res.send(`User ${key} deleted`);
    }
}

如果成功删除了对象的密钥,则delete语句中的if运算符将返回true。在某些情况下,您无法使用此运算符,请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete来检查它是否与您要执行的操作兼容。

编辑1:误解的问题,所以这是正确的delete方法

let userJSON = require('./users.json');

app.delete('/users/delete/:id', (req, res) => {
    let key = req.params.id;
    for( let i=0; i<userJSON.length; i++){
        if( userJSON[i].id === key ){
            userJSON.splice(i,1);
        }
    }
});

答案 1 :(得分:0)

当您将数据填充到字段中时,我假设您将拥有该记录的id

将其存储在变量中/或者您可以直接从获取的对象(object.id)中获取它

暂时将其存储在变量中。

假设下面是您提取并显示的对象数据:

var obj = {
   id:1,
   name: "Test",
   address:"Test Address"   
}
var objId = obj.id; //I'll use this id in AJAX request.

然后调用AJAX请求。

 $.ajax({
             type: "DELETE"
            , url: "users/delete/"+objId  
            , datatype: "datatype"
            , success: function (data) {
                 console.log(data);

                }   
                });

节点Js:

app.delete('/users/delete/:id', (req, res) => {
       let deleteId = req.params.id; //Get the id through req.params.id of the object you are going to delete
       let deleteObj = userJson.find(user => user.id == deleteId); // As you have only Id of the object, we want to get the entire object from the array. find() will fetch the object from the array whose id is equal to deleteId and assign it to deleteObj.
       let deleteIndex = userJson.indexOf(deleteObj); //Find the index of the object fetched from the JSON array.
       userJson.splice(deleteIndex,1); // Splice/ remove the object from the JSON Array.
      res.send(deleteObj); // Send the deleted object as response.
});