2012-03-29 2 views
1

MySQL 데이터베이스에서 데이터를 가져 와서 JSON 형식으로 출력하는 PHP 서버 측 파일을 호출하는 jQuery 함수를 만들었습니다. JSON 데이터는이 함수에서 템플릿으로 사용되어 DIV에 내 HTML 문서의 목록 항목으로 동적으로 삽입됩니다.jQuery JSON MySQL에서 템플릿

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> 

; 너는 발췌 부분을보고 너의 대답에서 적절하게 편집 해 줄 수 있겠 니? 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}]} 

답변

1

당신은 아약스의 성공은 구문 분석에 배열 Some_Guidance_Library을 참조하지 않습니다. 그냥 제거하는 것이 더 쉽습니다.

시도

$output = new stdClass(); 

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

변경 : 당신이 브라우저에 반환 된 JSON의 샘플을 제공하는 경우

$output = array(); 

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

도와 훨씬 쉽게 될 것이다. 바로 브라우저 콘솔에서 복사 할 수

편집 당신이 당신의 $.each 루프를 변경해야 제공 JSON을 바탕으로

: 내가 전에와 시도라고 생각했다

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

하지만 준 없음 결과를 다시 넣을 수 있습니다. 나중에 헤더 제목에 필요합니다. 내 JSON 데이터를 반환하겠습니까? – CelticParser

+0

json이 (가) 유효하지 않습니다. jsonlint.com에 입력하십시오. 모든 것에 큰 따옴표가 필요합니다. 여러 개의 키가 필요하지만 아약스 파싱에서 그 키를 사용해야하는 경우'$ Output [ 'Some_Guidance_Library'] = $ row'을 사용할 수도 있습니다 – charlietfl

+0

죄송합니다. 출력을 잘못 입력했습니다. 그래서 나는 그것을 편집했다. PHP 코드는 변경되지 않고 jsonlint.com에서 유효합니다. – CelticParser