dsozqcx9668 2016-03-21 00:17
浏览 31
已采纳

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

Hello i am trying to send fields from a from that i saved in a javascript object to a php server. I am using ajax but when i try to receive the object in php i get a length of 0 when debugging. Basically i can't receive the data. Please what did i do wrong.

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 code:

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

It displays a size of zero meaning it's not receiving the data. Please what did i do wrong

  • 写回答

3条回答 默认 最新

  • duansang8388 2016-03-21 00:29
    关注

    You cant access the post variable when posting JSON to the server so you need to do this.

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

    Then retrieve the fields

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

    Basically the same answer as techblu3 above, but a little more detailed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?