【问题标题】:jQuery JSON Templating from MySQL来自 MySQL 的 jQuery JSON 模板
【发布时间】:2012-03-29 19:38:03
【问题描述】:

我创建了一个调用 PHP 服务器端文件的 jQuery 函数,该文件从 MySQL 数据库中提取数据并以 JSON 格式输出。 JSON 数据在此函数中被模板化,以作为我的 HTML 文档中的列表项动态插入到 DIV 中。

JSON 数据很好 - 我使用工具对其进行了验证,如果我在浏览器中运行 PHP 脚本,它会正确显示(在 Chrome 中使用 JSONView)。但是,我无法让数据显示在 HTML 文档中。

我最初是在 PHP 文件中以 HTML 格式发送数据,这可以正常工作,但我遇到了其他问题 (plz see this SO question),所以我决定以另一种方式解决这个问题 - 改用 JSON 并对其进行模板化。

我正在尝试将数据库中的行:标签、标题、描述和 gotoURL 添加到透视 HTML 标记中:

<div id="navContent">
    <li id="navItem">
        <a href="">
        <h1>Label</h1>
        <h2>Title</h2>
        <p>Dispription</p>
       </a>
   </li>
</div>

我不知道我的编码有什么问题;您能否通过 sn-ps 查看并在您的答案中进行适当的编辑。谢谢

提供 PHP:

<?php
//MySQL Database Connect
include 'mylogin.php';

mysql_select_db("myDB");
$sql=mysql_query("select * from my_list");

$output = new stdClass();

while($row = mysql_fetch_assoc($sql)) {
    $output->Some_Guidance_Library[] = $row;
}

header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
echo (json_encode($output));

mysql_close();
?>

HTML 文档:

<html>
. . .
<head>
. . .
<script type="text/javascript">
    . . .
    var ajaxLoader = '';
    var dns = 'http://192.168.1.34';
    var navContent = '/andaero/php/my_list.php';
    var bodyContent = '/wiki/index.php/Document #content';

    <!-- ================ When Ready Do This ============================ -->
    <!-- **************************************************************** --> 
    $(document).ready(function(){
          loadNav(dns + navContent, "navContent");//<- This gets loaded into the navContent<div
          loadPage(dns + bodyContent, "bodyContent");
     });
    . . . 
</script>
</head>
<body>
    . . .
    <div id="navScrollContainer" class="navContentPosition">
        <div id="navContent">
        <li id="navItem">
            <a href="">
            <h1>Label</h1>
            <h2>Title</h2>
            <p>Dispription</p>
            </a>
        </li>
        </div>
    </div>
    . . .
</body>
<!-- ================ Functions ===================================== -->
<!-- **************************************************************** -->
. . .
<script type="text/javascript">

    /* --------------- Handle Pg Loading ----------------- */
    function loadPage(url, pageName) {
        $("#" + pageName).load(url, function(response){
            $('#navHeaderTitle').text($(response).attr('title'));
    //          transition("#" + pageName, "fade", false);
        });
    };

    function loadNav(url, divId) {//<-- THIS FUNCTION'S BROKE!!
        $.getJSON(url, function(data){
            $.each(data, function(){
                var newItem = $('#' + divId).clone();
                // Now fill in the fields with the data
                newItem.find("h1").text(this.label);
                newItem.find("h2").text(this.title);
                newItem.find("p").text(this.description);
                newItem.find("a").text(this.gotoURL);
                // And add the new list item to the page
                newItem.children().appendTo("#navScrollContainer")
            });
            //transition(pageName, "show");
        });
    };
</script>
</html>

返回的 JSON 数据:

{"Regulatory_Guidance_Library":[{"_id":"1","label":"AC","title":"Advisory Circulators","description":"Provides guidance such as methods, procedures, and practices for complying with regulations and requirements.","date":"2008-03-03","gotoURL":null},{"_id":"2","label":"AD","title":"Airworthiness Directives","description":"Legally enforceable rules that apply to aircraft, aircraft engines, propellers, and appliances.","date":"2012-06-08","gotoURL":"\/wiki\/index.php\/Airworthiness_Directive"},{"_id":"3","label":"CFR","title":"Code of Federal Regulations","description":"Official Rulemaking documents of the CFR in Title 14 and have been published in the Federal Register","date":"2012-01-31","gotoURL":null},{"_id":"4","label":"PMA","title":"Parts Manufacturer Approvals","description":"Parts Manufacturer Approvals","date":"2012-01-31","gotoURL":null},{"_id":"5","label":"SAIB","title":"Special Airworthiness Info Bulletins","description":"Bulletins issued by manufacturers to provide modification or inspection instructions.","date":"2012-01-31","gotoURL":null},{"_id":"6","label":"SFAR","title":"Special Federal Aviation Regulation","description":"Official Rulemaking documents that have changed the language of the CFR in Title 14 CFR for aviation.","date":"2012-01-31","gotoURL":null},{"_id":"7","label":"STC","title":"Supplemental Type Certificates","description":"Document issued by the Federal Aviation Administration approving a product (aircraft, engine, or propeller) modification","date":"2012-01-31","gotoURL":null},{"_id":"8","label":"TSO","title":"Technical Standard Orders","description":"Minimum performance standards issued by the FAA for specified materials, parts, processes, and appliances used on civil aircraft.","date":"2012-01-31","gotoURL":null},{"_id":"9","label":"TCDS","title":"Type Certificate Data Sheets","description":"Repository of Make and Model information of aircraft, engine or propeller including airspeed, weight, and thrust limitations, etc.","date":"2012-01-31","gotoURL":null}]}

【问题讨论】:

    标签: php json dom jquery


    【解决方案1】:

    您永远不会在 ajax 成功解析中引用数组 Some_Guidance_Library。可能更容易摆脱它。

    尝试改变

    $output = new stdClass();
    
    while($row = mysql_fetch_assoc($sql)) {
        $output->Some_Guidance_Library[] = $row;
    }
    

    收件人:

    $output = array();
    
    while($row = mysql_fetch_assoc($sql)) {
        $output[] = $row;
    }
    

    如果您提供返回浏览器的 json 样本,帮助会容易得多。可以直接从浏览器控制台复制

    编辑

    根据提供的 json,您需要将 $.each 循环更改为:

        $.each(data.Regulatory_Guidance_Library, function(){.......
    

    【讨论】:

    • 我之前曾想过并尝试过,但没有得到任何结果,所以我把它放回去了——我以后需要它作为标题。我会在我的 SO 中添加返回的 JSON 数据吗?
    • 你的 json 无效....把它放在 jsonlint.com 中。一切都需要双引号。如果您需要多个键,可以使用$output['Some_Guidance_Library']=$row,但您还需要在 ajax 解析中使用该键
    • 抱歉,我将输出错误地复制到我的 SO 中?所以我编辑了它。 php 代码未更改,并且在 jsonlint.com 上返回有效
    • 我在我的代码中做了一个小的编辑。 I added ('#' + divId)。现在我得到了 DOM 中显示的正确行数,但没有数据/文本。
    • 在我的帖子中添加了一个编辑,以更改您访问您提供的 json 的方式
    猜你喜欢
    • 2011-09-18
    • 1970-01-01
    • 2011-04-21
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 2013-10-10
    相关资源
    最近更新 更多