【问题标题】:send json data from javascript Ajax to php将 json 数据从 javascript Ajax 发送到 php
【发布时间】:2018-01-02 09:56:46
【问题描述】:

我正在尝试将 JSON 数据从 Javascript Ajax 解析为 PHP,但我在控制台中收到一条错误消息。如何将 json 编码为字符串格式。我做错了什么,这是我的附加代码。

function datasend(obj)
{
var flickr = {"name": "vivek", "age":"18"};
var data = JSON.stringify(flickr);

alert(data);
var request = new XMLHttpRequest();
request.open("POST", "getvalue.php", true);

request.setRequestHeader("Content-Type", "application/json");

request.onreadystatechange=function() {
      if (request.readyState == 4 && request.status == 200) {
    // Success!
           alert("yes");
       var resp = request.responseText;
       document.getElementById("sum").innerHTML=resp;
       } 
    }
request.send(data);
}
<?php

header('Content-type: application/json');
$json = file_get_contents('php://input');

$json_decode = json_decode($json, true);

$getnme=$json_decode->{'name'};
$json_response = json_encode($json_decode);
echo $getnme;

include 'db.php';

$sql= "UPDATE user1 SET name='".$getnme."' WHERE id=1";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} 
?>

我想通过更新查询将我的名字发送到数据库,这里我在解码 json 数据后没有得到我的名字。

【问题讨论】:

  • 你已经在php页面中传递了数据
  • @bhargav 是的,我通过 ajax 将 json 数据传递给 php

标签: javascript php json ajax database


【解决方案1】:

试试这个方法

写这个$getnme=$json_decode['name'];而不是$getnme=$json_decode-&gt;{'name'};

【讨论】:

    【解决方案2】:
    var request = new XMLHttpRequest();
    request.open("POST", "getvalue.php", true);
    xhttp.open("POST", "ajax_test.asp", true);
    xhttp.setRequestHeader("Content-type", "application/JSON");
    xhttp.send(JSON.stringify({"name": "vivek", "age":"18"}));
    

    在php端

    <?php
     $obj = json_decode($json);
        $getnme= $obj->name;
        echo $getnme;
        ?>
    

    【讨论】:

    • 我想以 json 格式而不是 x-www-form-urlencoded 格式发送我的数据..
    • JSON.stringify({"name": "vivek", "age":"18"}) 的输出不是application/x-www-form-urlencoded
    • 危险:你很容易受到SQL injection attacks的影响,你需要defend你自己。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 2012-08-11
    • 1970-01-01
    相关资源
    最近更新 更多