使用AJAX和JSON显示PHP的HTML内容

时间:2013-01-30 22:20:12

标签: php javascript jquery ajax json

我正在尝试从我的php文件中检索包含以下代码的信息。我的代码包含colums Email,FirstName,LastName和State。

$query = 'SELECT * FROM users WHERE LOWER(Email) = :email';
$stmt = $dbh->prepare($query);
$stmt->bindValue(':email', $email);
$stmt->execute();

if ($stmt->rowCount() == 1) {
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $firstName = $row['FirstName'];
    $lastName = $row['LastName'];
    $state = $row['State'];     
} echo json_encode($row);

我的Ajax代码是:

$.ajax({
    datatype: 'json',
    type: "POST",
    url: 'json-data.php',         
      success: function(data) {
        //called when successful
        $('#firstname').append(data.FirstName);     
      },
      error: function(e) {
        //called when there is an error
        //console.log(e.message);
      }

});

当我输入$('#firstname').append(data);时,它会显示以下输出:

{"FirstName":"Foo","LastName":"Bar","State":"Florida","Email":"foo@bar.com"}

如何制作它以便我只能获得名字并将其附加到div?

1 个答案:

答案 0 :(得分:1)

尝试:

var obj = jQuery.parseJSON(data);
$('#firstname').append(OBJ.FirstName);