对PHP的Ajax调用只返回" status 200 OK"但没有数据库结果的数组?

时间:2017-02-08 20:33:53

标签: php jquery mysql ajax pdo

我对使用PDO连接到mysql的php文件进行AJAX调用,然后将结果打印到控制台,但显示的唯一结果是:

 /*eslint-env jquery, browser*/
$(document).ready(function(){

$("#botono").click(function(){

    $.ajax({
        type: 'GET',
        url: 'phpf/retraerClientes.php',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function(response) {
            console.log(response);
        },
        error: function(error) {
            console.log(error);
        }
    });

 });

});

同样的调用与msqli和json一起显示结果,我做错了什么?

以下是代码:

自定义js:

ini_set('display_errors', 1); 
error_reporting(E_ALL);

define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'); 
if(!IS_AJAX) {die('');}

$configs = include('config.php');

 try{

$conn = new      PDO("mysql:host=".$configs["host"].";dbname=".$configs["database"],$configs["use    rname"],$configs["password"]);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "SELECT * FROM prueba";
$results = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC);
$jsonFinal = json_encode($results);
echo $jsonFinal;

}catch(PDOException $ex){
    echo 'Connection With Database Failed: '.$ex->getMessage();
}

PHP:

$accents = $conn->query("SET NAMES 'utf8'"); 

更新: 我找到了答案:

{{1}}

该行丢失,我的记录有重音,这使得最终的json损坏并造成误报

1 个答案:

答案 0 :(得分:1)

正如我所见,你需要在PHP中执行查询:

ini_set('display_errors', 1); 
error_reporting(E_ALL);

define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'); 
if(!IS_AJAX) {die('');}

$configs = include('config.php');

 try{

$conn = new      PDO("mysql:host=".$configs["host"].";dbname=".$configs["database"],$configs["use    rname"],$configs["password"]);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "SELECT * FROM prueba";
$results = $conn->prepare($sql)->execute()->fetchAll(PDO::FETCH_ASSOC);
$jsonFinal = json_encode($results);
echo $jsonFinal;

}catch(PDOException $ex){
    echo 'Connection With Database Failed: '.$ex->getMessage();
}

http://php.net/manual/es/pdostatement.fetchall.php