$ .ajax()不接受php数组

I'm using ajax to return results from a table (mysql). Ajax calls are made using jquery. Databases are accessed using PDOs.

PHP

    function fetchQuestions() {
            $database = "answerMe";  // the name of the database.
            $server = "127.0.0.1";  // server to connect to.
            $db_user = "name";  // mysql username to access the database with.
            $db_pass = "password";  // mysql password to access the database with.
            $table = "questions";
            $result = "";

            try {
              $testh = new PDO ("mysql:host=$server;dbname=$database", $db_user, $db_pass);
              $testh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
              $testh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
              $sql = "select COUNT(*) from questions";
              $pstatement = $testh->prepare($sql);
              $success = $pstatement->execute();
              $num = $pstatement->fetchColumn();
              $sql = "select * from $table";
              $pstatement = $testh->prepare($sql);
              $success = $pstatement->execute();
              print("Fetch all of the remaining rows in the result set:
");
              $result = $pstatement->fetchAll(PDO::FETCH_COLUMN, 1);
              return $result;
            }
            catch(PDOException $e)
            {
              echo "Following error was encountered <br />";
              echo $e->getMessage();
            }
    }
    $function = $_POST['function'];    
    $response = array();
    $data = "";

    switch($function) {
             .
             .
             .      

             case('recData'):
                //$qs = array('w','k');
                $qs = fetchQuestions();
                $response['records'] = $qs;
                    break;
    }    
    echo json_encode($response);

Jquery(ajax part)

    function AjaxReq(){
            this.sendSuccess = false;
            this.recSuccess = false;
            this.send = sendData;
            this.rec = recData;
    }
    .
    .
    .
    function recData() {
            $.ajax({
               type: "POST",
               url: "ajax.php",
               data: {  'function': 'recData',
                                    },
               dataType: "json",

               success: function(data){
                       alert('rec succeeded');
                       this.recSuccess = true;
                       for(var i = 0; i < data.records.length; ++i) {
                                    $("#details").append(data.records[i]);
                            }
               },
            });
    }

Jquery (calling ajax)

    $(document).ready(function(){
            var reqTest = new AjaxReq();
            $("#done").bind('click',function(){
                    reqTest.rec();
            });
    });

In the PHP code, case 'recData', if I uncomment //$qs = array('w','k');, I get the results.

This made me conclude maybe $qs wasn't an array probably. But using is_array(), its was proven otherwise.

I have tried my best to keep irrelevant code away from here. Any help would be appreciated. Thank you.

try to use this java script var_dump library to debag Your data response. https://github.com/kvz/phpjs/blob/master/functions/var/var_dump.js

I have trimmed your code as outlined in sscce. You should avoid using Try/Catch blocks unless you are going to handle the catched exception eg if database down.

$database = "answerMe";  // the name of the database.
$server = "127.0.0.1";  // server to connect to.
$db_user = "name";  // mysql username to access the database with.
$db_pass = "password";  // mysql password to access the database with.
$testh = new PDO ("mysql:host=$server;dbname=$database", $db_user, $db_pass);
$testh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$testh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "select * from $table";
$pstatement = $testh->prepare($sql);
$success = $pstatement->execute();
$result = $pstatement->fetchAll(PDO::FETCH_COLUMN, 1);
var_dump($result); 

var_dump($result) dumps information about a variable. If the result is that required you can incrementally add features testing as you go.

EDIT Assuming result is satisfactory.

  1. Change var_dump($result) to echo json_encode($result)
  2. Add header('Content-Type: application/json') after <?php
  3. Save code at ajaxtest.php
  4. Use the following code to show JSON (Using getJSON)
  5. If results satisfactory incorporate into your own code

CODE

$(document).ready(function() {
    $.getJSON('ajaxtest.php', function(data) {
        $.each(data, function(i, item) {
            $('#result').append('<p>' + data[i].records + '</p>');
        });
    });   
});

EDIT 2 Rather than use $sql = "select * from $table" you should use $sql = "select `records` from $table". This would eliminate needing to use fetchColumn(). fetchColumn(1) retrieves column 2 NOT column 1

The print statement in the following lines created the problem.

    $success = $pstatement->execute();
    print("Fetch all of the remaining rows in the result set:
");
    $result = $pstatement->fetchAll(PDO::FETCH_COLUMN, 1);

The meddled with the JSON's encoding and created all the trouble. Removing it solves the problem.

Ajax call must always accompany error handlers to help debugging.

    error: function(xhr, textStatus, errorThrown) {
            alert('An error occurred! ' + ( errorThrown ? errorThrown :
            xhr.status ));