本文介绍了来自MySQL的jQuery JSON模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created a jQuery function that calls on a PHP server-side file that pulls data from a MySQL database and outputs it in JSON format. The JSON data is template'd in this function to be dynamically inserted into a DIV as list items in my HTML document.

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

The JSON data is good - I validated it with a tool and if I run the PHP script in a browser, it displays correctly (using JSONView in Chrome). However, I cant get the data to display in the HTML doc.

我最初是在PHP文件中以HTML格式发送数据,并且可以正常工作,但是我遇到了其他问题( plz看到了这一点问题),因此我愿意以另一种方式进行此操作-使用JSON并对其进行模板化.

I was originally sending the data as HTML in the PHP file and this worked correctly but I was having other issues (plz see this SO question) so I desided to go about this in another way - using JSON instead and templateing it.

我正在尝试从数据库中添加以下行:标签,标题,说明和&将gotoURL插入透视图HTML标签:

I'm trying to add from the database rows: label, title, discription, & gotoURL into the perspective HTML tags:

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

我不知道自己的编码有什么问题;您能否浏览一下代码片段并在答案中进行适当的编辑. thnx

I don't know what I have wrong in my coding; could you please look thru the snippets and edit appropriately in your answer. Thnx

服务的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}]}

推荐答案

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

You never refer the array Some_Guidance_Library in your ajax success parsing. Likely easier to just get rid of it.

尝试更改

$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示例,将会更容易获得帮助.可以直接从浏览器控制台复制它

Would be a lot easier to help if you provided sample of the json returned to browser. Can copy it right from browser console

编辑

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

Based on json provided you would need to change your $.each loop to:

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

这篇关于来自MySQL的jQuery JSON模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 14:55