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

Ajax GET项目中window.location失效及iziToast.then报错求助

解决iziToast.success后跳转失效及TypeError错误

问题根源

控制台报错Uncaught TypeError: Cannot read properties of undefined (reading 'then'),是因为iziToast.success()方法不返回Promise对象,你试图链式调用.then()就会触发这个错误,直接导致后续的页面跳转代码无法执行。

修复方案

下面提供两种可靠的解决方式:

方案1:使用iziToast内置的onClosed回调

iziToast支持配置onClosed函数,会在提示框关闭时自动执行,完美匹配你的需求:

function buy_product(cid) {
    $.ajax({
        url: '/buyProduct/' + cid,
        type: 'get',
        success: function(response) {
            var result = $.parseJSON(response);
            if (result["success"]) {
                iziToast.success({
                    theme: 'dark',
                    message: result["message"],
                    timeout: 3000,
                    // 提示框关闭后执行跳转
                    onClosed: function() {
                        window.location = "/my/products";
                    }
                });
            } else {
                alert("Error");
            }
        },
        error: function(xhr, err) {
            alert("Error");
        }
    });
}

方案2:用setTimeout配合超时时间

既然已经设置了提示框3秒后自动关闭,直接用setTimeout延迟相同时间执行跳转:

function buy_product(cid) {
    $.ajax({
        url: '/buyProduct/' + cid,
        type: 'get',
        success: function(response) {
            var result = $.parseJSON(response);
            if (result["success"]) {
                iziToast.success({
                    theme: 'dark',
                    message: result["message"],
                    timeout: 3000
                });
                // 延迟3秒后跳转
                setTimeout(function() {
                    window.location = "/my/products";
                }, 3000);
            } else {
                alert("Error");
            }
        },
        error: function(xhr, err) {
            alert("Error");
        }
    });
}

额外优化建议

可以给Ajax请求添加dataType: 'json'配置,让jQuery自动解析JSON响应,省去手动调用$.parseJSON的步骤:

$.ajax({
    url: '/buyProduct/' + cid,
    type: 'get',
    dataType: 'json', // 自动解析响应为JSON对象
    success: function(result) { // 直接使用解析后的result
        if (result.success) {
            // 后续逻辑
        }
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 07:05:21