无法使用ajax/jquery获取要显示的json对象
我对JSON了解不多,尽管我做了很多尝试,但我始终无法将JSON返回到ajax中,并使用jquery显示它。无法使用ajax/jquery获取要显示的json对象,jquery,ajax,json,Jquery,Ajax,Json,我对JSON了解不多,尽管我做了很多尝试,但我始终无法将JSON返回到ajax中,并使用jquery显示它。我试图做的是,在加载用户配置文件时,使用JSON对象将数据发送到ajax。 [更新]php代码: <?php include(dirname(__FILE__). '/../script/config.php'); session_start(); $id = $_POST['u_search']; $email = $_SESSION['Email']; foreach($pdo
我试图做的是,在加载用户配置文件时,使用JSON对象将数据发送到ajax。
[更新]php代码:
<?php include(dirname(__FILE__). '/../script/config.php');
session_start();
$id = $_POST['u_search'];
$email = $_SESSION['Email'];
foreach($pdo->query("SELECT * FROM Users WHERE ID='$id'") as $row) {
//$firstname = $row['FirstName'];
//$lastname = $row['LastName'];
$pic = $row['Pic'];
$id = $row['ID'];
$u_email = $row['Email'];
}
$firstname = "Jason";
$lastname = "Born";
$data = array("success"=> true,"inpt"=>"<p>Hello there! I am " . $firstname . " " . $lastname . "</p>");
echo json_encode($data);
header("Content-Type: application/json");)
?>
<?php $pdo = null; ?>
function op_prof(obj) {
var value = obj.id;
var dataString = "{'u_search':'"+value+"'}";
$("#co_profile").show();
$(".searchbox").val('');
$("#usr_suggest").hide();
$.ajax({
type: "POST",
url: '/script/profile.php',
dataType: 'json',
data: dataString,
cache: false,
success: function(data) {
alert(console.log(data));
alert(data);
$("#co_profile").html(data.inpt).show();
location.hash = 'profile' + 'id=' + dataString;
}
});
};
编辑:当我使用dataType:'json'
时,success
中没有任何内容运行,但当我删除它时,它们运行..编辑:当我使用
datatype:'json'
而不是datatype:'json'
时,运行success
中的代码。我使用了alert(console.log(data))代码>,表示“未定义”
编辑:我使用的是//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js
如果将datatype:json放在json字符串格式中,则表示必须发送数据:“”,即使在服务器端,变量名也应该匹配,以便它可以读取您发送的值
例如:
datatype:'json',
data : JSON.stringify({'u_search':'value'})
使用JSON.js文件将对象转换为字符串
var dataString = "{'u_search':'"+value+"'}";
dataType: 'json',
data: dataString,
编辑:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
试试这个
$.post("/script/profile.php",{dataString:dataString},function(data){
alert(console.log(data));
alert(data);
$("#co_profile").html(data.inpt).show();
location.hash = 'profile' + 'id=' + dataString;
}, "json"); // USing JSON here for the returned value from server...
在profile.php文件中,必须解码json格式。记住在名为dataString的变量中收集解码的json值首先尝试在success
中console.log(data)
并在您的问题中打印日志。在我的示例中,我能够根据您的偏好正确加载json数据。如果你愿意,我可以和你分享。但是首先显示您的console.log(数据)。在success
运行中没有任何内容。。那是有线的。。我把console.log(数据)
成功但是当我删除数据类型:“json”
时,success
中的所有内容都会运行如果运行profile.php文件,它会显示任何错误吗?因为我怀疑在您的第一种情况下使用'$id'
和'$pic'
。