尝试从php获取json数据。我想将我的mysql raw编码为json并通过ajax将其发送给用户。但在我的页面中它没有显示数据。我犯了什么错误?
phpScript
<?php
require_once("../configuration.php");
$con=new mysqli($hostname,$dbusername,$dbpass,$dbname);
if (mysqli_connect_errno($con)) {
die('The connection to the database could not be established.');
}
$news_name=$_POST['news_name'];
function newsdetails($news_name){
global $con;
$querynews="SELECT * FROM news WHERE id='$news_name'";
$resultnews=$con->query($querynews);
$rownews=$resultnews->fetch_array();
echo json_encode($rownews);
}
newsdetails($news_name);
?>
Jquery的:
$.ajax({
url: "/function/news_user_page.php",
type: "POST",
data: {news_name:'84'}
success:function(data, textStatus, jqXHR)
{
$("#test").html(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
})
答案 0 :(得分:0)
一些事情:
.html()
输入的对象。你可能想要.html(data.some_field)
; 答案 1 :(得分:0)
在数据后添加逗号:{news_name:&#39; 84&#39;}然后添加dataType:&#39; JSON&#39;
答案 2 :(得分:0)
$news_name=$_POST['news_name:'];
应该没有:
$news_name=$_POST['news_name'];
甚至更好,也可以逃避可能的sql注射:
$news_name=mysql_real_escape_string($_POST['news_name']);
答案 3 :(得分:0)
在PHP脚本中定义响应头:
header('Content-type: application/json');
并设置
dataType: 'json'
on $ .ajax()call。