[英]Posting JSON to php script server side fails
这是我的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
json_decode可能失败,返回NULL
值。 执行var_dump($result)
和var_dump($input)
来查看从客户端和json_decode获得的内容。
你为什么不尝试使用
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);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.