简体   繁体   English

ajax响应使用pdo返回[object]并显示我的查询

[英]ajax response returns [object] using pdo and show my query

getting querystring sent back with my ajax response. 得到我的ajax响应发回的querystring。 The ajax works i know the id is being passed and i have echo the variable in php and it show correct but when i use json encode i get a an [object] alert in my and the response looks like this 阿贾克斯的作品,我知道id被传递,我已经在php中回显了变量,它显示正确,但是当我使用json编码时,我收到了[object]警报,响应如下所示

response: 响应:

{"queryString":"SELECT * FROM ContactInfo WHERE id = :id"}

php: PHP:

$id = $_POST['id'];
if (empty($id)) {
    echo "no id";
}
try {
    $conn = new PDO('mysql:host=localhost;dbname=test;charset=utf8', user, pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);   
    $stmt = $conn->prepare('SELECT * FROM ContactInfo WHERE id = :id');
    $stmt->execute(array('id' => $id));
    echo json_encode( $stmt);
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }

JS: JS:

    $.ajax({
        type: "POST",
        timeout: 6000,
        data : {id: myid}, // add if using post
        dataType : 'json', //text
        crossDomain: false,
        cache: false,
        async: true,
        url: requrl,
        success: function(data) {
            alert(data);                        
        }

You need to pass the result array use fetch() : 您需要使用fetch()传递结果数组:

$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode( $result );

Then jQuery will return an object here's how you can access it: 然后jQuery将返回一个对象,这里是如何访问它的方法:

success: function(data) {        
      alert(data.FirstName); 
}

EDIT: I noticed you're just returning one row so it's not fetchAll(). 编辑:我注意到您只返回一行,所以它不是fetchAll()。

Try this: 尝试这个:

$result = $stmt->execute(array('id' => $id));
echo json_encode($result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM