从php返回的json无法解析为jQuery dataTables

I have a simple mysql database table with library books. I am using a php page to retrieve the list of books. This is what it returns:

php get_books.php

{"iTotalRecords":"1","aaData":[{"author":"Tim Powers","title":"The Anubis Gates","genre":"Fiction","publisher":null,"year":null,"location":"Bookshelf","notes":null}]}

In jQuery dataTables, I have:

<script >
    $(document).ready(function() {
    $('#books').DataTable({
        "bServerSide": true,
        "sAjaxSource": "./get_books.php"
    });
});
</script>

When I run the web page with that script I get an alert:

DataTables warning (table id = 'books'): DataTables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error.

I can't find what the formatting error is. How should the data be formatted.

Here is the php page that does the return of the JSON data:

<?php
    $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
    $offset = ($page-1)*$rows;
    $result = array();

    include 'conn.php';

    $rs = mysql_query("select count(*) from books");
    $row = mysql_fetch_row($rs);
    $result["iTotalRecords"] = $row[0];
    $rs = mysql_query("select * from books limit $offset,$rows");

    $items = array();
    while($row = mysql_fetch_object($rs)){
        array_push($items, $row);
    }
    $result["aaData"] = $items;

    echo json_encode($result);

?>

What should the return look like and how do I produce it?

duanbi2760
duanbi2760 这就是“setheaders”的含义:stackoverflow.com/a/4064468/622391
4 年多之前 回复
dongwupu5991
dongwupu5991 我查看了Safari中的Web开发人员工具,但没有找到实际的响应。该错误似乎表明解析器遇到了一个'>',它在php页面中,而不是在页面的响应中。
4 年多之前 回复
dongxi1943
dongxi1943 您应该使用浏览器的工具检查ajax请求,并确保响应符合预期。
4 年多之前 回复
dsmgcse8876
dsmgcse8876 不明白你的意思。我在哪里放类型(...)。setheader是什么意思?
4 年多之前 回复
duanjuete9206
duanjuete9206 尝试typeof(data-returned-here)并验证该值是对象而不是字符串。有时您需要设置标题来识别json,
4 年多之前 回复

2个回答

There are many problems both with your JS and PHP code.

If you have less than a few thousands records in books table I would recommend disabling server-side processing mode by removing "bServerSide": true to enable client-side processing mode.

JavaScript:

$(document).ready(function() {
    $('#books').DataTable({
        "ajax": "get_books.php",
        "columns": [
           { "data": "author" },
           { "data": "title" },
           { "data": "genre" },          
           { "data": "location" }         
        ]
    });
});

PHP:

<?php   
    include 'conn.php';

    $rs = mysql_query("select author, title, genre, location from books");

    $result = array();
    $items = array();
    while($row = mysql_fetch_object($rs)){
        array_push($items, $row);
    }
    $result["data"] = $items;

    header("Content-type: application/json");
    header("Cache-Control: no-cache, must-revalidate");

    echo json_encode($result);
?>

HTML

<table id="books" class="display tablesorter">
   <thead>
      <tr>
         <th>Author</th>
         <th>Title</th>
         <th>Genre</th>
         <th>Location</th>
      </tr>
   </thead>
</table> 

See this jsFiddle for code and demonstration.

If you have more than a few thousands records, you will gain more performance by using server-side processing mode. But in this case I recommend using ssp.class.php helper library that comes in jQuery DataTables distribution (see examples/server_side/scripts folder).

dsd57259
dsd57259 我觉得get_books.php的路径不正确。 指定脚本的完整路径,例如“ajax”:“/ fulll / path / to / get_books.php”并查看是否有效。
4 年多之前 回复
drvkf88226
drvkf88226 是什么原因导致脚本运行get_books.php而不是只读它? 看来你必须执行PHP代码。 你是怎样做的?
4 年多之前 回复
donglong7338
donglong7338 我做到了。 使用这些框架做事情不应该这么复杂。 我可以用“刮擦”来写下所有内容,省力和不确定。 框架应该更容易。 相反,这是一个猜谜游戏。
4 年多之前 回复
dongtuo3370
dongtuo3370 确保已包含对header()的调用以设置响应的内容类型。
4 年多之前 回复
dongxian7489
dongxian7489 我通过JSONLint运行了我的get_books.php输出,它说它是有效的。
4 年多之前 回复
duanci9305
duanci9305 当我将文件用于JSON数据时,我终于能够得到我想要的东西。 我在控制台中运行get_books.php文件并将输出粘贴到JSON.txt文件中。 当我有ajax:“。/ JSON.txt”时,一切正常! 我想对于一个小数据集,我可以使用该文件并使其最终更新? 但是,我希望能够使用从get_books.php返回的JSON。 它没有给我一个解析错误,但它也没有填写数据。
4 年多之前 回复
duanniu3385
duanniu3385 我已经更新了添加位置列的答案。
4 年多之前 回复
doupafu6980
doupafu6980 非常感谢Gyrocode! 这让我超越了解析错误! 我仍然没有在DataTable中看到任何内容。 我想让jQuery和DataTable为我做这件事。 使用上面描述的JSON,这是我对表的所有内容:<table id =“books”class =“tablesorter”> <thead> <tr> <th>作者</ th> <th>标题</ th > <th>类型</ th> <th>位置</ th> </ tr> <tbody> </ tbody> </ table>
4 年多之前 回复



发现问题,这对我来说是愚蠢的!
OS X El Capitan(10.11.2),php文件没有得到 由Safari或任何其他浏览器识别,因为它们位于我的主目录中,而不是在/ Library / WebServer / Documents根目录中用于apache! </ p>

我将项目移动到该目录中,因为我无法设置使用我的用户目录〜/ Sites,因为您可以在El Capitan之前使用我的用户目录〜 )。</ p>

有了这个改变,php文件会被执行,因为它们包含在ajax参数中,一切正常!</ p>

谢谢你的每一个 你的帮助。 很抱歉浪费时间,但我的test.php工作了,但我没有注意到它在Web服务器根目录中!</ p>
</ div>

展开原文

原文

Found the problem and it was stupid on my part! On OS X El Capitan ( 10.11.2 ), php files were NOT getting recognized by Safari or any other browser because they were in my home directory and not in the /Library/WebServer/Documents root for apache!

I moved my project into that directory as I could not get things set up to use my user directory ~/Sites as you could before El Capitan ( will work on that some more in the future ).

With that change, the php documents get executed as they are included in the ajax argument and all works fine!

Thanks every one for your help. Sorry to have wasted time, but my test.php worked, but I hadn't noticed that it was in the web server root directory!

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐