gpt4 book ai didi

javascript - 空数组 AJAX

转载 作者:行者123 更新时间:2023-12-03 07:03:29 25 4
gpt4 key购买 nike

所以我进行了一些搜索,希望找到解决我的问题的方法,但没有运气。我基本上试图将数据传递到 ajax 函数中,但是当它将数据传递到我的 php 文件时,它只返回一个空数组(是的,有一些关于此的主题,找不到任何适合我的需求),这里是控制台输出:Array()

这很奇怪,因为就在 ajax 函数之前我记录了数据,并且它毫无问题地打印出每个部分。发布 URL 是准确的,直接从我的表单中工作正常。我尝试使用响应而不是通过函数传递的数据,但也没有运气。提前致谢!

这是JS文件

$(document).ready(function() {
$('form.ajax').on('submit', function() {

var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = [];

that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();

data[name] = value;
});
console.log(data); /////THIS LINE HERE ACTUALLY PRINTS DATA
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
console.log(data);
}
});

return false;

});
});

这是我的 PHP

<?php //removed the issets and other checkers for ease of readability

print_r($_POST);

?>

更新:我尝试将 method:"POST"添加到我的 ajax 函数中,但它似乎仍然打印出空白数组...也许我应该将所有内容都转换为 GET?

最佳答案

jQuery ajax() 使用 GET 作为默认方法。您需要为 POST 请求提及 method: POST

method (default: 'GET')

$.ajax({
url: url,
method: "POST",
type: type,
data: data,
success: function(data) {
console.log(data);
}
});

或者您也可以使用post()

关于javascript - 空数组 AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36931540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com