javascript - 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 是您发布到的页面而不是您从变量中获取的页面,对吗?
解决方案
我认为问题在于您没有为 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。
推荐阅读
- python - 我收到 FileNotFoundError:[Errno 2] 没有这样的文件或目录:'user.txt'。我怎么称呼它不同?
- typo3 - 将字段添加到 TYPO3 模板以获取全球站点信息?
- azure-devops - Azure 管道运行时评估的变量传递了一个参数
- javascript - 最简单的是在 javascript 中显示未定义的元素
- prometheus - 如何在 Prometheus 中使用时间单位创建警报?比如“最近 2 分钟平均响应时间超过 5 秒”
- python - 减去从字符串转换的日期时间时,total_seconds() 是错误的
- vba - 使用文本框内容宏重命名 Powerpoint 对象
- javascript - 混淆更新根目录并在链接中添加文本
- python - 如何在唯一列值上合并数据框?
- vue.js - Vue Router 的资源路径在重新加载时中断