PHP parsererror ajax get返回字符串数组

时间:2017-01-11 20:48:05

标签: php jquery arrays ajax

我在尝试绕过" parsererror"时遇到了问题。尽管在devtools中有一个字符串数组的响应,但是从我的ajax请求返回。我有一个click事件,它发出ajax请求从数据库中提取信息。开发工具的结果是:

1["1","admin","admin@admin.com","test","2017-01-11 00:00:00"]

我原以为它是一个json对象{}。

我为click事件编写的代码是:

$('#viewProfile').on('click', function() {
    $.ajax({
        type: 'GET',
        url: 'api.php',
        data: "",
        cache: false,
        dataType: 'json',
        success: function(data) {
            var id = data[0];
            var name = data[1];
            $('#userDetails').html("<p>ID: " + id + " Name: " + name + "</p>");
        },
        error: function(request, error) {
            $('#userDetails').html("<p>There was a problem: " + error + "</p>");
        }


    });


});

我为api.php写的php

    session_start();
echo $_SESSION['user_session'];

//DECLARE VARS FOR DB
$db_host = "localhost";
$db_name = "dbregistration";
$db_user = "root";
$db_pass = "";
$db_tablename = "tbl_users";

//CONNECT TO DB
include 'dbconfig.php';
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
$dbs = mysqli_select_db($db_con, $db_name);

//QUERY DB FOR DATA
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
$array = mysqli_fetch_row($result);

//RETURN RESULT
echo json_encode($array);

我已经尝试在api.php中使用json_encode($ array,JSON_FORCE_OBJECT)以及将数据类型更改为HTML,这显然不起作用。简而言之,我的目标是能够触发click事件,发送ajax请求以从数据库中检索信息,基于用户ID然后将其返回到页面上的#userDetails id。我被困在试图绕过似乎是我的障碍的字符串数组。

2 个答案:

答案 0 :(得分:1)

删除此行:

echo $_SESSION['user_session'];

并改变这一点:

$array = mysqli_fetch_row($result);

到此:

$array = mysqli_fetch_assoc($result);

编辑:您还应该检查各种与数据库相关的语句的成功/失败:

$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name) or die("there was a problem connecting to the db");
$dbs = mysqli_select_db($db_con, $db_name) or die("Could not select db");

以及

$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
if (!$result) {
    die("query failed");
}

答案 1 :(得分:-1)

这需要删除echo $_SESSION['user_session']它将返回到ajax调用,因为它在json上,返回错误。