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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)