weixin_33711647 2014-07-20 16:12 采纳率: 0%
浏览 113

JSON返回HTML结果

I'm using dataTable and I'm having the Json parse error. Here is my code:

jQuery(function($){
         $('#allusers').dataTable({
             "sAjaxSource": document.URL+"/allusers.php"
         });

        $.ajax({
            url: document.URL+"/allusers.php",
            success: function(data){
                alert (data);
            }
        });
    });

So inserted the $.ajax part so that I could see the data being returned. (Well I could also see it using firebug, just wanna make sure) and the response that I am getting is the HTML code instead of the JSON object.

here is the snippet of allusers.php:

$dataArr['aaData'] = Array();
$res = $mysqli->query($query);
$numrows = $res->num_rows;
$output = array('iTotalRecords' => $numrows, "iTotalDisplayRecords" => 10, "aaData" => array() );
if ($res = $mysqli->query($query)){
    while($row = $res->fetch_array(MYSQLI_ASSOC)){
        $r = Array();
        foreach($row as $key=>$value){
            $r[] = $value;
        }
        $output['aaData'][] = $r;
    } 
} else 
    die(mysql_errno());
$output['err'] = 'hello';
header('Content-Type: application/json');
echo json_encode($output);
exit();

I already tried var_dump($r) to check the contents of $output and I don't see a problem with it.

So the result that I'm getting is:

<!DOCTYPE html>
<html class="home">
<head>
<title>User List</title>
...

it basically returns the html content of the whole page. Is the problem within the javascript or php? Thanks in advance for the help!

  • 写回答

2条回答 默认 最新

  • weixin_33674976 2014-07-21 10:11
    关注

    Not sure if your PHP framework respects requested datatypes, but you could start by requesting JSON specifically. Either specify:

    $.ajax({
            url: document.URL+"/allusers.php",
            dataType: "application/json",
            success: function(data){
                alert (data);
            }
        });
    

    or use the jquery json shortcut:

    $.getJSON("url", data, callbackFuntion);
    

    The default for the $.ajax() method is to intelligently guess the output, so it seems weird it doesn't pick up on your content-type.

    My last idea would be that you specified php headers and footers globally somehow, so they are added to your output?

    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料