PHP 服务器无法使用 ajax 接收 javascript 对象


PHP server unable to receive javascript object using ajax

您好,我正在尝试将字段从保存在javascript对象中的字段发送到php服务器。我正在使用 ajax,但是当我尝试在 php 中接收对象时,调试时长度为 0。基本上我无法接收数据。请问我做错了什么。

Javascript code:
    //fields from from saved in an object.
    var obj={
      'user_name': username,
      'pwd': psswd1,
      'user_email': email,
      'user_phone': mobile,
      'sec_quest1': question1,
      'ans1': answer1,
      'sec_quest2': question2,
      'ans2': answer2,
      'user_address': address,
      'user_userInfo': user_info
  };
   console.log(obj);
   var data = JSON.stringify(obj)
   var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//document.getElementById("txtHint").innerHTML = xhttp.responseText;
    alert(xhttp.responseText);
   }
 } 
 xhttp.open("POST", "server.php", true);
 xhttp.setRequestHeader("Content-type", "application/json");
 xhttp.send(data);
}

PHP代码:

<?php
  $obj = json_decode($_POST["data"]);
 echo 'Name: '.sizeof($obj);
?>

显示的大小为零,表示它没有接收数据。请问我做错了什么

将 JSON 发布到服务器时无法访问 post 变量,因此需要执行此操作。

$str = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str, true);

然后检索字段

$name = $response['user_name'];
$phone = $response['user_phone'];
// etc
// or just $response[0], $response[1], $response[2] etc etc

与上面的techblu3基本相同的答案,但更详细一些。

您可能正在发布原始数据,这些数据可以用这种方式在 php 中访问

    $obj = json_decode(file_get_contents("php://input"),true);
    // true parameter is used to decode as array
    // you can make it false to use object
    echo $obj["user_name"];

一种解决方案是序列化数据,以便您可以使用标头 x-www-form-urlencoded 发送数据。

 serialize = function(obj) {
  var str = [];
  for (var p in obj)
   if (obj.hasOwnProperty(p)) {
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
   }
  return str.join("&");
 }
 var obj = {
  'user_name': 'John Doe',
  'user_email': 'john@doe.net',
  'user_phone': '2122221111',
 };
  var params = serialize(obj);
  var url = "https://url.net";

  console.log(params);
  var xhr = new XMLHttpRequest();
  xhr.open("POST", url, true);
  //Send the proper header information along with the request
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.send(params);

您的 PHP 文件将包括

 <?php echo 'Name: '.sizeof($_POST); ?>