You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JavaScript点击删除按钮时获取restaurant_name执行收藏删除操作

问题:无法获取restaurant_name完成收藏餐厅删除操作
  • 删除接口URL格式为 {{baseUrl}}/favorites/restaurant_name/user_name,已能从sessionStorage获取登录用户的user_name,但无法获取restaurant_name
  • 尝试两种方式均失败:通过URL传参获取未成功;点击按钮时将restaurant_name存入sessionStorage也未生效,sessionStorage中无对应值
  • 发现首次执行console.log(restaurant_name)显示undefined,原因是此时尚未跳转到带参数的URL(如localhost3000/favorites.html?restaurant_name=Astons),只有跳转后才能从URL中获取到值

获取收藏列表代码

function getFavorites() {
    var response = "";
    var request = new XMLHttpRequest();
    user_name = sessionStorage.getItem('user_name');
    request.open("GET", "https://abakandkansdjk.execute-api.us-east-1.amazonaws.com/favorites/" + user_name, true);

    request.onload = function () {
        response = JSON.parse(request.responseText);
        console.log(response);

        var HTML = ""
        for (let i = 0; i < response.Count; i++) {
            console.log(response.Items[i].restaurant_name)

            HTML += '<div class="col-md-3 box " style="background-color: #debc99;">' +
                '<div class="card" style="margin:15px -5 20px -5; ">' +
                '<a class="card-block stretched-link" href="#"></a>' +
                '<img class="card-img-top" src="' + response.Items[i].image + '" style="margin-left: 1px;width: 220px; margin-top: -15px;"'+ 
                'alt="Card image cap">' +
                '<div class="card-body">' +
                '<h5 class="card-title"></h5>' +

                '<h4 style="margin-top: 0px; color:black">' + response.Items[i].restaurant_name + '</h4>' +
                '<span class="badge badge-secondary float-right"'+ 
                'style="background-color: #8d4843; margin-top: -5px;">Cuisine</span>' +
                '<a style="color: black; margin-top: -5px;" onclick="deleteFavorites(); sessionStorage.setItem("favRestaurant",' + response.Items[i].restaurant_name +');" href="favorites.html?restaurant_name=' + response.Items[i].restaurant_name + '"'+ '><u>Delete</u></a>' +

                '</div>' +
                '</div>' +

                '</div>'
        }

        document.getElementById('favoritesList').innerHTML = HTML;
    };
    request.send();
}

删除收藏代码

function deleteFavorites() {
    var response = "";
    var user_name = sessionStorage.getItem("user_name")
    console.log(user_name)

    var alert1 = confirm("Are you sure you want to delete this item from your favourites? This is irreversible.");

    if (alert1 === true) {
        window.location.href="http://localhost:3000/favorites.html?restaurant_name=" + restaurant_name
        console.log(restaurant_name)
        var urlParams = new URLSearchParams(window.location.search);
        var restaurant_name = urlParams.get("restaurant_name");
        var request = new XMLHttpRequest();
        var url = "https://aba3bajndc.execute-api.us-east-1.amazonaws.com/favorites/" + restaurant_name + "/" + user_name
        console.log("restaurant_name")
        request.open("DELETE", url, true);
        request.onload = function () {
            if (response.message == "favorites deleted") {
                alert('This restaurant has been deleted from favorites!');

            }
            else if (response.message != "favorites deleted") {
                alert('Unable to add to favorites, try again!');

            }
        }
        request.send();
    }
  
}

修复方案

1. 修正Delete按钮的点击逻辑

直接将restaurant_name作为参数传递给删除函数,同时阻止页面默认跳转(跳转会中断当前JS执行):

// 修改getFavorites函数中拼接Delete按钮的代码
HTML += '<div class="col-md-3 box " style="background-color: #debc99;">' +
    // ... 其余代码保持不变 ...
    '<a style="color: black; margin-top: -5px;" onclick="deleteFavorites(\'' + response.Items[i].restaurant_name + '\')" href="javascript:void(0);"><u>Delete</u></a>' +
    // ... 其余代码保持不变 ...

2. 重写deleteFavorites函数

直接使用传入的参数执行删除请求,无需跳转页面,删除成功后刷新收藏列表:

function deleteFavorites(restaurant_name) {
    var user_name = sessionStorage.getItem("user_name");
    // 校验参数是否存在
    if (!user_name || !restaurant_name) {
        alert('缺少必要参数,请重新登录后尝试');
        return;
    }

    var alert1 = confirm("确定要从收藏中删除这家餐厅吗?此操作不可撤销。");
    if (alert1 === true) {
        var request = new XMLHttpRequest();
        // 对特殊字符进行编码,避免URL拼接出错
        var url = "https://aba3bajndc.execute-api.us-east-1.amazonaws.com/favorites/" + encodeURIComponent(restaurant_name) + "/" + encodeURIComponent(user_name);
        request.open("DELETE", url, true);
        
        request.onload = function () {
            var response = JSON.parse(request.responseText);
            if (response.message === "favorites deleted") {
                alert('这家餐厅已从收藏中删除!');
                // 删除成功后重新加载收藏列表
                getFavorites();
            } else {
                alert('删除失败,请重试!');
            }
        };
        
        // 添加网络错误处理
        request.onerror = function() {
            alert('网络请求失败,请检查网络连接');
        };
        
        request.send();
    }
}

原代码失败原因说明

  • 原按钮点击逻辑中,先执行deleteFavorites()再存入sessionStorage,但页面跳转会立即刷新上下文,导致sessionStorage的设置未完成就被中断
  • deleteFavorites函数中先执行页面跳转,跳转后原函数上下文被销毁,后续的请求代码根本不会执行
  • URL参数获取逻辑在跳转后,但跳转后的页面是全新的上下文,无法关联原删除请求

内容的提问来源于stack exchange,提问作者lalala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 21:45:38