首页 > 解决方案 > AJAX 在我尝试将数据发布到的 url 上显示错误

问题描述

我正在尝试制作一个页面,该页面将使用 AJAX 将数组发布到下一页,以便 PHP 可以访问它。 https://www.kvcodes.com/2015/10/passing-javascript-array-to-php-through-jquery-ajax/

我已使用此页面上的第一个示例作为教程。这是第一页的代码

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
if (sessionStorage.getItem('idsarray') !== '') {
    var string = sessionStorage.getItem('idsarray');
    const array = string.split(",");
    array.shift();
    console.log(array)
    $.ajax({ 
        type: "POST", 
        url: "detailselection.php", 
        data: { idsarray : array }, 
        success: function() { 
            alert("Success"); 
        }    
    }); 
                            
   $('#continuebutton').on("click", location.href = "detailselection.php");
}

这应该将我的数组发布到下一页 detailselection.php 然后打开该页面但我在控制台中收到此错误,即使警报显示成功

有人能告诉我这意味着什么以及如何解决吗?错误

编辑:我用完整的 url (http://localhost/.php/detailselection.php) 替换了 AJAX url,这给了我完全相同的错误。然后我尝试更改 location.href 也给出了相同的错误,但更新以反映新的 url。这意味着错误出现在 location.href 行,而不是我最初想到的 AJAX url。但是该错误似乎与 AJAX 有关,因为当我删除它时没有错误。

编辑#2:我也尝试过这样的代码,它在成功函数中打开下一页。这没有显示任何错误消息,但变量仍然没有被传递到下一页

$('#continuebutton').on("click", function () {
    $.ajax({ 
    type: "POST", 
    url: "http://localhost/.php/detailselection.php", 
    data: { variable: 'yes'}, 
    success: function() { 
        alert("Success"); 
        window.location 
        = "http://localhost/.php/detailselection.php";
    }   
    }); 
})

只是为了确认我正确理解 AJAX,url 是您发布到的页面而不是您从变量中获取的页面,对吗?

标签: javascriptphpjqueryajax

解决方案


我认为问题在于您没有为 AJAX 提供有效的 url 来发布。您需要指定要从中获取的域detailselection.php

if (sessionStorage.getItem('idsarray') !== '') {
    var string = sessionStorage.getItem('idsarray');
    const array = string.split(",");
    array.shift();
    console.log(array)
    $.ajax({ 
        type: "POST", 
        url: "myDomain/detailselection.php", 
        data: { idsarray : array }, 
        success: function() { 
            alert("Success"); 
        }    
    }); 
                            
   $('#continuebutton').on("click", () => {
        location.href = "myDomain/detailselection.php"
    });
}

此外,不要忘记在 url 中指定您的端口号,尤其是在开发中,因为默认情况下,浏览器请求端口 80 用于 http 请求,端口 443 用于 https 请求。如果您使用的端口不是这些端口(您可能正在开发中,因为 1024 以下的端口是保留的),您需要在 url 中指定端口。例如,如果您在端口 3000 上提供文件,您的 url 将是127.0.0.1:3000/path/to/your/file

注意:正如其他人所提到的,您必须为事件侦听器提供一个函数,而不是简单的 equals。


推荐阅读