douyan3478 2017-03-08 09:56
浏览 33
已采纳

AJAX POST到PHP无法正常工作

I am trying to POST a JSON to PHP where it should be decoded and pushed to MySQL database.

This is my JavaScript code.

    var dictstring = "{sensorid: \""+ name +"\", x: " +pos.x +" ,y: "+pos.y+"}";
                    console.log(dictstring);

                    $.ajax({
                        type: "POST",
                        contentType: 'application/json; charset=utf-8',
                         dataType: "json",
                        url: "myfile.php",
                        data: JSON.stringify(dictstring),
                        success: function(data){
                        alert('Success');
                        },
                    error: function(e){

                    console.log(e.message);
                        }
                    });

And this is my PHP code

<?php


$jsonData = file_get_contents('php://input');

$data_back = json_decode($jsonData);
$unit = $data_back->{"sensorid"};
$x_axis = $data_back->{"x"};
$y_axis = $data_back->{"y"};


// Create connection
$con=mysqli_connect("xxxxxxx:xxxx","xxxxx","xxxx","xxxxxxxx");

// Check
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

//Insert Values
$sql_hm = "INSERT INTO xxxx(unit, x_axis, y_axis)
VALUES ('$unit', $x_axis, $y_axis)";

if ($con->query($sql_hm) === TRUE) {
    echo "values inserted successfully"; 

} else {
     echo "No data ";
}



?>

I know the PHP part works - I tried POSTing JSON data with contentType: application/json from a REST client app and it works. But when I am trying it with my Javascript code, it isnt POSTing. I can see the "dictstring" string value in console. I cannot see the "Success" alert too. Interestingly, "Success" alert is shown if I remove the dataType: "json" line. But, POSTing is still not happening as I cannot see the values in database.

What am I missing here?

  • 写回答

4条回答 默认 最新

  • doufangxie0203 2017-03-08 10:03
    关注
    var dictstring = "{sensorid: \""+ name +"\", x: " +pos.x +" ,y: "+pos.y+"}";
    

    You have a string.

    data: JSON.stringify(dictstring),
    

    Which you then convert to a JSON representation of that string.

    $data_back = json_decode($jsonData);
    

    Which you decode to a string.

    $unit = $data_back->{"sensorid"};
    

    Which you try to treat like an object.


    Start with an object, not a string:

    var dictstring = { sensorid: name, x: pos.x, y: pos.y };
    

    … you probably want a different variable name too.

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

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误