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

时间:2022-12-04 19:04:05

I am trying to retrieve information from my php file which contains the following code. My code contains the colums Email, FirstName, LastName, and State.

我正在尝试从包含以下代码的php文件中检索信息。我的代码包含列电子邮件、名、名和状态。

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

My Ajax code is:

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

});

});

When I type $('#firstname').append(data);, it shows me the following output:

当我输入$('#firstname').append(data);

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

How do I make it so I can get only the first name and append it to a div?

如何才能只获取第一个名称并将其附加到div中呢?

1 个解决方案

#1


1  

try with:

试一试:

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

#1


1  

try with:

试一试:

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