【问题标题】:Send JSON object with POST使用 POST 发送 JSON 对象
【发布时间】:2014-02-07 20:24:30
【问题描述】:

我想用 POST 发送一个 JSON 对象

var user = {
    "first_name": first_name.value,
    "last_name": last_name.value,
    "age": age.value,
    "email": email.value
};   

这就是我发送对象的方式:

var request;
var url = 'ajax_serverside_JSON.php';
var destination;

function ajax_call(src, jsonObj, dst, method) {

    this.src = src;
    destination = dst;
    this.objJSON = jsonObj;
    this.request = getXMLHttpRequest();
    this.request.onreadystatechange = getResponse;
    if (method == 'POST') {
        sendPostRequest(objJSON);
    }
    return;
}

function sendPostRequest(objJSON) {
    request.open('POST', url, true);
    request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    request.send(JSON.stringify(objJSON));
    return;
}

function getXMLHttpRequest() {
    try {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera,Safari
            request = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            request = new ActiveXObject("Microsoft.XMLHTTP");
        }
    } catch (e) {
        alert('The browser doesn\'t support AJAX: ' + e);
        request = false;
    }
    return request;
}

function getResponse() {
    if (request.readyState == 4 && request.status == 200) {
        document.getElementById(destination).innerHTML += request.response;
    }
}

问题:如何读取服务器端 php 中的对象?发送的 json 的密钥是什么?

echo var_dump ( $_POST );显示

  array (size=0)
  empty

有什么问题?

编辑后

我将代码更改为:

this.objJSON = jsonObj;

request.send("user=" + JSON.stringify(this.objJSON));

我尝试阅读 JSON obj:

<?php
if (isset ( $_POST ['user'] )) {
    $obj = json_decode ( $_POST ['user'] );
    echo "isset";
} else {
    echo "is not set ";
    echo var_dump ( $_POST );
}
?>

...还是一样的:

is not set

array (size=0)
  empty

【问题讨论】:

    标签: javascript ajax json xmlhttprequest


    【解决方案1】:

    将您的功能分解为核心 3 行:

    function ajax_call(src, jsonObj, dst, method) {
    

    jsonOBJ 在本地范围内设置为变量。

    this.objJSON = jsonObj;
    

    jsonOBJ 被复制到this.objJSON

    sendPostRequest(objJSON);
    

    仍然没有局部变量 objJSON,因为 Javascript 不会自动将 this 视为局部范围的一部分,因此发送 null,因此为空的 $_POST

    改为发送jsonOBJthis.objJSON 即可。

    【讨论】:

    • 能否请您看一下“编辑后”,也许我没有做对。感谢您的帮助
    【解决方案2】:

    试试:

    request.send("obj="+JSON.stringify(objJSON));
    

    它是一个键值对,我猜你缺少键。

    【讨论】:

      【解决方案3】:

      我不确定 PHP 是否可以自动将 JSON 解析为 $_POST 变量。您应该将 JSON 放入普通 POST 变量的值中:

      request.send('data=' + encodeURIComponent(JSON.stringify(objJSON));
      

      并使用默认的 Content-Type。然后在 PHP 中你可以这样做:

      var_dump(json_decode($_POST['data']));
      

      您还需要修复一个 Javascript 变量,如 Niels Keurentjes 的回答中所述。

      【讨论】:

      • 我知道为什么但是request.send('data=' + encodeURIComponent(JSON.stringify(this.objJSON))); 不起作用...它给了我Undefined index: data 和以前一样的东西
      • 我还检查了 POST 选项卡,发现有火错误,我看到我有条目“ data=%7B%22first_name%22%3A%22das%22%2C%22last_name%22%3A%22dsa %22%2C%22age%22%3A%22dsadsa%22%2C%22email%22%3A%22dsadsa%22%7D"
      • 该数据看起来正确。你摆脱了setRequestHeader 电话吗?
      • 抱歉,我不确定。我只是使用jQuery,让它担心细节。
      • 字符串 'data={"first_name":"fdsfds","last_name":"fdsf","age":"dsfds","email":"fdsdfs"}' (长度=78 )
      【解决方案4】:
      <script>
      var user = {
                      "first_name" : first_name.value,
                      "last_name" : last_name.value,
                      "age" : age.value,
                      "email" : email.value
                  };
      
      $.customPOST = function(data,callback){
        $.post('your_php_script.php',data,callback,'json');
      }
      
      $(document).ready(function() {
          //suppose you have a button "myButton" to submit your data
          $("#myButton").click(function(){
              $.customPOST(user,function(response){
               //on the server side you will have :
               //$_POST['first_name'], $_POST['last_name'], .....
               //server will return an OBJECT called "response"
               //in "index.php" you will need to use json_encode();
               //in order to return a response to the client
               //json_encode(); must have an array as argument
               //the array must be in the form : 'key' => 'value'
              });
              return false;
          });
      </script>
      

      【讨论】:

        【解决方案5】:

        对于您的原始 Ajax 请求,您必须从 php://input 读取请求正文并对其进行解码。

        <?php
        $post = json_decode(file_get_contents('php://input'));
        if (isset ( $post ['user'] )) {
            echo "isset";
        } else {
            echo "is not set ";
            echo var_dump ( $post );
        }
        

        【讨论】:

        • 这是处理 json 的正确方法,将 json 以编码形式发布的变量(get/post)放在服务器端。
        猜你喜欢
        • 2022-06-14
        • 2011-11-11
        • 2016-05-24
        • 1970-01-01
        • 2014-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多