如何通过ajax将mysql结果作为jSON传递 [英] How to pass mysql result as jSON via ajax

查看:158
本文介绍了如何通过ajax将mysql结果作为jSON传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何通过ajax JSON将mysql查询的结果传递到html页面. ajax2.php

I'm not sure how to pass the result of mysql query into html page via ajax JSON. ajax2.php

$statement = $pdo - > prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement - > execute(array(':key2' => $key2, ':postcode2' => $postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while ($row = $statement - > fetch()) {
    echo $row['Name']; //How to show this in the html page?
    echo $row['PostUUID']; //How to show this in the html page?
    $row2[] = $row;
}
echo json_encode($row2);

如何通过上面的ajax将上述查询结果传递到html页面中?

How to pass the above query result to display in the html page via ajax below?

我的ajax

$("form").on("submit", function () {
    var data = {
        "action": "test"
    };

    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "ajax2.php", //Relative or absolute path to response.php file
        data: data,
        success: function (data) {
            //how to retrieve the php mysql result here?
            console.log(data); // this shows nothing in console,I wonder why?
        }
    });
    return false;

});

推荐答案

您的json编码应类似于:

Your json encoding should be like that :

 $json = array();
 while( $row = $statement->fetch()) {
     array_push($json, array($row['Name'], $row['PostUUID']));
 }

    header('Content-Type: application/json');
    echo json_encode($json);

在您的javascript部分中,您无需执行任何操作即可取回数据,它通过成功函数存储在data var中. 您可以只显示它,并使用它在网页上做任何想做的事情

And in your javascript part, you don't have to do anything to get back your data, it is stored in data var from success function. You can just display it and do whatever you want on your webpage with it

这篇关于如何通过ajax将mysql结果作为jSON传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆