如何通过jquery正确发送php中的JSON

How to send JSON in php via jquery correctly

本文关键字:php 中的 JSON 何通过 jquery      更新时间:2023-09-26

我正在将JSON发送到后端服务器,但我对如何正确处理它感到困惑,我正在阅读echo (json_decode($_POST));行不通,但是 echo (json_decode(file_get_contents("php://input")));,但实际上我试图在客户端输出响应alert(respon);但没有显示

0_12_e2_contentType_JSON.html

<html>
<head>
    <script type="text/javascript" src="jquery-2.0.3.min.js"></script>
</head>
<body>
<script >
    $(function(){
        $.ajax({
            url: "fragment/0_12_e2_contentType_JSON.php",
            type: "POST",
            contentType:"application/json; charset=utf-8",
            data: {
                "name":"hans" ,
                "id":10
            },
            success: function (respon)
            {
               alert(respon);
            },
            error:function(e){
            alert('Ajaxnya error');
               }
        });
  });
</script>
</body>
</html>

0_12_e2_contentType_JSON.php

<?php
echo (json_decode(file_get_contents("php://input")));
?>

我的问题是它已经正确了吗?但是为什么它什么都不输出?谢谢

如果要

发送contentType:'application/json'则需要自己串化数据

 $.ajax({
        url: "fragment/0_12_e2_contentType_JSON.php",
        type: "POST",
        contentType:"application/json; charset=utf-8",
        data: JSON.stringify({ "name":"hans" ,"id":10}),
        success: function (respon)
        {
           alert(respon);
        },
        error:function(e){
        alert('Ajaxnya error');
           }
    });

大多数人不会覆盖默认contentType并使用 php 接收$_POST

不清楚你的问题,反正最后你似乎想从服务器回答你通过ajax发送的内容......如果是这种情况,我建议使用json_encode...不json_decode

<?php
header('Content-Type: application/json');
echo (json_encode($_POST));
?>