如何使用AJAX GET请求显示获取的stdclass对象

时间:2015-06-17 03:57:20

标签: php mysql ajax pdo

我已成功使用PDO使用PDO::FETCH_OBJ方法从我的数据库中获取数据,然后查询返回:

Array (
       [0] => stdClass Object
       (
        [id] => 2
        [title] => Johnny Sims
        [img] => 
        [description] => 
        [school] => 
        [location] => 1
        [url] => 
        [tablename] => 2
        [votes] => 5
        [name] => President Candidates
        [Numopinions] => 6
    )

[1] => stdClass Object
    (
        [id] => 2
        [title] => Jeremy Pinto
        [img] => 
        [description] => 
        [school] => 
        [location] => 1
        [url] => 
        [tablename] => 2
        [votes] => 4
        [name] => Presidential Candidates
        [Numopinions] => 6
    )

[2] => stdClass Object
    (
        [id] => 2
        [title] => Sarah Bushels
        [img] => 
        [description] => 
        [school] => 
        [location] => 1
        [url] => 
        [tablename] => 2
        [votes] => 3
        [name] => Presidential Candidates
        [Numopinions] => 6
    )
    )

如果这是回显的话,如何使用AJAX GET请求与此数据进行交互?

2 个答案:

答案 0 :(得分:1)

我假设您希望在JavaScript中与它进行交互,在这种情况下,您可以json_encode($array)然后将其输出到内容类型标头设置为application / json的页面。

如果您随后使用AJAX请求该页面并将结果加载到var中,它将自动解析为JavaScript数组。

答案 1 :(得分:1)

这只是您的方案的一种表示。

的index.php

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<!-- jQuery -->
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<div id="result"></div>

<script>
    $(document).ready(function(){
        var userId= 1; //this can be anything like a gobal variable or an user input, etc
        $.ajax({
            url: "ajax.php",
            type: "GET",
            data: {id : userId}, //userId is the variable that you are going to pass to ajax.php
            dataType: "json",
            success: function(data) {
                //your logic what do you want to do with it
                $("#result").html( data.title + '-' + data.name);
            },
            error: function(xhr, textStatus, errorThrown) {
                alert( "Request failed: " + textStatus );
            }
        })
    });
</script>
</body>
</html>

ajax.php

<?php
//you logic here, this is just a dumy example

$id = isset($_GET['id']) ? $_GET['id'] : 0;
$db_records = array(
    array(
        "id" => 2,
        "title" => 'Jeremy Pinto',
        "img" => '',
        "description" => '',
        "school" => '',
        "location" => 1,
        "url" => '',
        "tablename" => 2,
        "votes" => 4,
        "name" => 'Presidential Candidates',
        "Numopinions" => 6
    ),

    array (
        "id" => 2,
        "title" => 'Sarah Bushels',
        "img" => '',
        "description" => '',
        "school" => '',
        "location" => 1,
        "url" => '',
        "tablename" => 2,
        "votes" => 3,
        "name" => 'Presidential Candidates',
        "Numopinions" => 6
    )
);

print json_encode($db_records[$id]);