1

I don't know much about JSON and have never been able to return something with JSON into ajax and show it using jquery despite of my many tries.
What I am trying to do is, send data using JSON object to the ajax while loading the profile of a user.

[Updated] php code:

<?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; ?>

Updated Ajax:

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;
    }
  });
};

edit: When I use dataType: 'json' , nothing in success runs but when I remove it, they run..

edit: When I use datatype: 'json' instead of dataType: 'json' the codes in success run. I used alert(console.log(data)); , it says "undefined"

edit: I am using //ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js

4

3 回答 3

1

如果您输入 datatype:json 意味着您必须以 json 字符串格式发送 data:"" ,即使在服务器端,变量名称也应该匹配,以便它可以读取您发送的值。

例子:

datatype:'json',
data : JSON.stringify({'u_search':'value'})

使用 JSON.js 文件将对象转换为字符串。

于 2013-05-17T05:41:59.677 回答
1
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>
于 2013-05-17T05:47:55.117 回答
0

尝试这个。

$.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 格式。记得将解码后的 json 值收集到一个名为 dataString 的变量中

于 2013-05-17T07:42:04.210 回答