AJAX调用的contentType:“应用/ JSON的”不工作 [英] Ajax call with contentType: 'application/json' not working
问题描述
我有一个Ajax调用,发送表单数据到PHP函数。因为我看了很多,使用的contentType:应用/ JSON的
是我想给它一个尝试和最佳实践。但不幸的是我的剧本时,我用它不返回任何东西。如果我删除了,该脚本做的事情是应该做的。
你有任何想法的原因可能是为什么?谢谢!
$('#形式)。递交(函数(五){
即preventDefault();
VAR含量= $(本).serialize()+&放大器; AJAX = 1;
$阿贾克斯('应用程序/班/控制器/ contactForm.php',{
键入:POST,
//的contentType:应用/ JSON的,
数据类型:JSON,
数据:内容,
成功:函数(结果){
执行console.log(结果);
}
});
})
和我的PHP:
如果(使用isset($ _ POST ['阿贾克斯'])及和放大器; $ _ POST ['阿贾克斯'] ==='1'){
回声json_en code(validateForm($ _ POST));
}
在使用的contentType:应用/ JSON的
您将无法依靠 $ _ POST
被填充。 $ _ POST
中只填入表格-CN codeD的内容类型。
因此,你需要阅读从PHP原始输入您的数据是这样的:
$输入=的file_get_contents('php的://输入');
$对象= json_en code($输入);
当然,如果你想发送应用程序/ JSON
,其实你应该送JSON,你不这样做。你要么需要直接建立对象序列化到JSON,或者你需要做这样的事情 - 的转换表单数据JS对象与jQuery - 连载的形式对象
说实话,你的情况,因为你正在处理的表单数据,我不太想用例使用应用程序/ JSON
是存在的。
I have an ajax call, that sends form data to a php function. Since I read a lot that using contentType: 'application/json'
is best practice I wanted to give it a try as well. But unfortunately my script doesn't return anything when I use it. If I remove it, the script does what it is supposed to do.
Do you have any idea what the reason might be and why? Thank you!
$('#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);
}
});
})
and my PHP:
if(isset($_POST['ajax']) && $_POST['ajax'] === '1') {
echo json_encode(validateForm($_POST));
}
When using contentType: 'application/json'
you will not be able to rely on $_POST
being populated. $_POST
is only populated for form-encoded content types.
As such, you need to read your data from PHP raw input like this:
$input = file_get_contents('php://input');
$object = json_encode($input);
Of course if you want to send application/json
you should actually send JSON, which you are not doing. You either need to build the object serialization to JSON directly, or you need to do something like this - Convert form data to JS object with jQuery - to serialize the object from the form.
Honestly in your case, since you are dealing with form data, I don't quite think the use case for using application/json
is there.
这篇关于AJAX调用的contentType:“应用/ JSON的”不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!