gpt4 book ai didi

php - 使用 contentType : 'application/json' not working 的 Ajax 调用

转载 作者:可可西里 更新时间:2023-10-31 22:09:10 24 4
gpt4 key购买 nike

我有一个 ajax 调用,它将表单数据发送到 php 函数。因为我读了很多关于使用 contentType: 'application/json' 是最佳实践的文章,所以我也想尝试一下。但不幸的是,我的脚本在使用时没有返回任何内容。如果我删除它,脚本会执行它应该执行的操作。

您知道原因可能是什么吗?谢谢!

$('#Form').submit(function(e) {
e.preventDefault();

var content = $(this).serialize() + "&ajax=1";

$.ajax('app/class/controller/contactForm.php', {
type: "POST",
//contentType: 'application/json',
dataType: 'json',
data: content,
success: function(result) {
console.log(result);
}
});
})

和我的 PHP:

if(isset($_POST['ajax']) && $_POST['ajax'] === '1') {
echo json_encode(validateForm($_POST));
}

最佳答案

当使用 contentType: 'application/json' 时,您将无法依赖 $_POST 被填充。 $_POST 仅适用于表单编码的内容类型。

因此,您需要像这样从 PHP 原始输入读取数据:

$input = file_get_contents('php://input');
$object = json_decode($input);

当然,如果你想发送 application/json 你实际上应该发送 JSON,但你并没有这么做。您要么需要直接将对象序列化构建为 JSON,要么需要执行类似这样的操作 - Convert form data to JavaScript object with jQuery - 序列化表单中的对象。

老实说,在您的情况下,由于您正在处理表单数据,我不太认为存在使用 application/json 的用例。

关于php - 使用 contentType : 'application/json' not working 的 Ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20295080/

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