使用Ajax和JQuery从PHP文件获取JSON数据

时间:2014-03-25 11:59:58

标签: javascript php jquery ajax json

我有问题。 我正在尝试使用JQuery中的$ .ajax从PHP文件中获取一些日期

我的JQuery代码:

$.ajax({
url: "warcaby_s.php",
type: "POST",
data: { check: "1", id: id, player: player },
dataType: "json",
success: function(data)
{
    player_active = 1;
    timer = data.timeleft;
    pionki[0] = data.row_1.split("");
    pionki[1] = data.row_2.split("");
    pionki[2] = data.row_3.split("");
    pionki[3] = data.row_4.split("");
    pionki[4] = data.row_5.split("");
    pionki[5] = data.row_6.split("");
    pionki[6] = data.row_7.split("");
    pionki[7] = data.row_8.split("");

    $("#players").text("Grają: " + data.player_1 + " i " + data.player_2);

    rysuj_plansze(context);
}
});

我的PHP文件是:

    if ((isset($_REQUEST['check'])) && ($_REQUEST['check'] == 1))
{
    $zapytanie = 'select * from warcaby where id = '.$_REQUEST['id'];
    $wykonaj = mysqli_query($pol, $zapytanie);
    $wiersz = mysqli_fetch_array($wykonaj, MYSQLI_ASSOC);

    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header('Content-type: application/json');

    echo json_encode(array("player_1"=>$wiersz['player_1'], "player_2"=>$wiersz['player_2'], "row_1"=>$wiersz['row_1'], "row_2"=>$wiersz['row_2'], "row_3"=>$wiersz['row_3'], "row_4"=>$wiersz['row_4'], "row_5"=>$wiersz['row_5'], "row_6"=>$wiersz['row_6'], "row_7"=>$wiersz['row_7'], "row_8"=>$wiersz['row_8'], "timeleft"=>$wiersz['timeleft']));
}

PHP输出:

{"player_1":"mat","player_2":"mat","row_1":"02020202","row_2":"20202020",
"row_3":"00000000","row_4":"00000000","row_5":"00000000","row_6":"00000000",
"row_7":"01010101","row_8":"10101010","timeleft":27}

至于我 - 纯JSON

Firebug标题:

Nagłówki odpowiedzi

Cache-Control   no-cache, must-revalidate

Connection  Keep-Alive

Content-Length  207

Content-Type    application/json

Date    Tue, 25 Mar 2014 11:53:49 GMT

Expires Mon, 26 Jul 1997 05:00:00 GMT
Keep-Alive  timeout=5, max=58

Server  Apache/2.2.21 (Win32) PHP/5.3.10

X-Powered-By    PHP/5.3.10


Nagłówki żądania

Accept  application/json, text/javascript, */*; q=0.01

Accept-Encoding gzip, deflate

Accept-Language pl,en-US;q=0.7,en;q=0.3

Content-Length  22

Content-Type    application/x-www-form-urlencoded; charset=UTF-8

Host    localhost

Referer http://localhost/warc/warcaby1.php?start=1

User-Agent  Mozilla/5.0 (Windows NT 6.0; rv:28.0) Gecko/20100101 Firefox/28.0

X-Requested-With    XMLHttpRequest

不幸$.ajax.error函数返回parsererror

我不知道我做错了什么。 你有什么建议我应该怎样做才能使它发挥作用?

2 个答案:

答案 0 :(得分:0)

正如tobias-kun指出的那样,输出缓冲区可能会说“隐藏的字符”,为什么不尝试使用ob_clean函数来阻止比预期更多的输出。

答案 1 :(得分:0)

尝试添加

die;

执行后

echo json_encode( ...