在 PHP 中处理 json 请求 [英] handle json request in PHP

查看:15
本文介绍了在 PHP 中处理 json 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在进行ajax调用时,当contentType设置为application/json而不是默认的x-www-form-urlencoded时,服务器端(在PHP中)无法获取post参数.
在以下工作示例中,如果我在 ajax 请求中将 contentType 设置为application/json",则 PHP $_POST 将为空.为什么会这样?如何在 PHP 中正确处理 contentType 为 application/json 的请求?

When making an ajax call, when contentType is set to application/json instead of the default x-www-form-urlencoded, server side (in PHP) can't get the post parameters.
in the following working example, if I set the contentType to "application/json" in the ajax request, PHP $_POST would be empty. why does this happen? How can I handle a request where contentType is application/json properly in PHP?

$.ajax({
    cache: false,
    type: "POST",
    url: "xxx.php",
    //contentType: "application/json",
    processData: true,
    data: {my_params:123},
    success: function(res) {},
    complete: function(XMLHttpRequest, text_status) {}
});

推荐答案

<?php
   var_dump(json_decode(file_get_contents('php://input')));
?>

这篇关于在 PHP 中处理 json 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆