dongmi19720408 2015-06-05 13:38
浏览 74
已采纳

将PHP数组传递给jQuery会返回空数组或通知

I'm trying to read some information from a MySQL database using php and then pass the results to jquery and log them in the console.

To read from the database I use:

public function getQuestions(){
    $query = 'SELECT * FROM Question';
    $statement = $this->db->prepare($query);
    $statement->execute();
    $questions = [];
    while($row = $statement->fetch()){
        $questions[] = array(
            'QuestionID' => $row['QuestionID'],
            'Content' => $row['QuestionContent']
        );
    }
    return $questions;
}

where $this->db is a PDO object.

Then this method is called from

<?php

include_once 'classes/DatabaseAdapter.php';

$dba = new DatabaseAdapter();
echo $dba->getQuestions(); // Array to String conversion error.

And that is then called from jQuery with:

$.ajax({
    url: 'questions.php',
    method: 'post'
}).done(function(data){
    console.log('done');
    console.log(data);
});

The problem I'm having is when I encode the output as json in PHP with json_encode() I get an empty string in the console and decode it in jQuery with JSON.parse(). Then I try passing it without encoding and get a notice saying Array to String conversion in PHP line with echo.

  • 写回答

2条回答 默认 最新

  • dpauf28808 2015-06-05 13:56
    关注

    Try this way. You can adapt the code to your getQuestions() function

    Php code

    //PDO connection
    
    $host   = "";
    $user   = "";
    $dbname = "";
    $pass   = "";
    
    try {
      $DBH = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass,
                        array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
    }
    
    //PDO Database query and Json encode
    
    $STH = $DBH->prepare("SELECT * FROM Question");
    $STH->execute();
    $result = $STH->fetchAll();
    $data = array();
    $data['items'] = $result;
    echo json_encode($data);
    

    Jquery

    //$.getJSON is a shorthand Ajax function
    
    $.getJSON("questions.php", function(data) {
    console.log(data);
    $.each(data.items, function(i, value){
    console.log(value.thecolumnnameinmysqltable);
    })
    })
    

    In the Php im creating an array for the purpose that you can add extra data and retrieve it .eg

    $data = array();
    $data['data'] = array("one", "two", "three", "four");
    $data['items'] = $result;
    echo json_encode($data);
    

    and to retrieve the $data['data'] array in Jquery you do

        var one   = data.data[0];
        var two   = data.data[1];
        var three = data.data[2];
        var four  = data.data[3];
    

    Getjson info -- http://api.jquery.com/jquery.getjson/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64