Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

AJAX同步请求,想要将数据库中的一些信息显示在前端,但是获取的值是空的

PHP:
<?PHP
    header("Content-Type: text/html; charset=utf-8");
    include('conn.php');//链接数据库
    $sql = "select * from article";
    $res = mysqli_query($conn,$sql);
    // 创建backResult空对象
    $arr = [];
    // 执行while循环语句,循环数据库查询的结果集,并使用fetch_array()取出每条记录
    while ($row = mysqli_fetch_array($res)){
        $arr[] = $row['id'];
        $arr[] = $row['article_name'];
    }
    // 打印返回给前台的json数据
    echo json_encode($arr);
?>
AJAX:
<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url : "./php/active.php",//后台请求的数据,用的是PHP
            type : "post",//请求方式
            async : false,//是否异步请求
            success : function(msg) {?//如果请求成功,返回数据。
                var res = eval("("+msg+")");
                console.log(res);
                $("#article_name").append(res.article_name);
                $("#id").append("[ID:" + res.id + "]");
                console.log(res.article_name);
                console.log(res.id);
            },
        })
    })
</script>

想要在HTML前端页面输出数据库中的article_name和id,我按照网上的方法,console.log(res)能同样获取返回的值:
▼(2) ["1", "4124214"]
0: "1"
1: "4124214"
length: 2
?__proto__: Array(0)
undefined
undefined
res.article_name和res.id都获取不到值,文章说可以直接获取,我却获取不了,该怎么修改能获取到值?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你后台返回的并不是json格式的对象,而是一个数组,所有点不出来
用res[0],res[1]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...