0

这是我的jquery代码:

var jsObj = {"user_id":5, "login":"hsm"};
var str_json = JSON.stringify(jsObj);
$.post("json_handler.php", str_json)
    .done(function(){
        alert('data sent successfully');
        window.location = "http://localhost/quranMapping/php/json_handler.php";
    })
    .fail(function(){
        alert('fail');
    });

注意:我进行了重定向以检查问题出在哪里。

这是我的 php 代码(json_handler.php文件):

<?php

//create a DB connection
$con=mysqli_connect("127.0.0.1","root","","my_db");

$input = file_get_contents('php://input');
$result = json_decode($input);

echo $result->user_id;
mysql_close($con);
?>

由于错误,请查看附图,

我该如何纠正这样的问题?

在此处输入图像描述

更新:当我使用$input = $_POST['str_json'] 错误是undefined index

4

2 回答 2

1

json_decode 可能失败,返回一个NULL值。做var_dump($result)var_dump($input)看看你从客户端和 json_decode 得到什么。

于 2013-08-02T15:16:45.637 回答
0

你为什么不尝试使用

JS:

var jsObj = {"user_id":5, "login":"hsm"};
var str_json = JSON.stringify(jsObj);
$.post("json_handler.php", {"str_json" :str_json})
            .done(function(){
                alert('data sent successfully');
                window.location = "http://localhost/quranMapping/php/json_handler.php";
            })
            .fail(function(){
                alert('fail');
            });

PHP:

<?php

//create a DB connection
$con=mysqli_connect("127.0.0.1","root","","my_db");

$input= $_POST['str_json']
$result = json_decode($input);

echo $result->user_id;
mysql_close($con);

?>
于 2013-08-02T15:29:18.323 回答