2013-08-21 69 views
0

我想從mysql中獲取數據,並用json_encode來回應它。那麼我的JQUERY將通過$.getJSON捕獲JSON並將結果附加到我的<ul>從mysql獲取數據,然後通過JSON顯示

IM試圖找出爲什麼數據被抓獲JQUERY沒有在我的index.php打印

這是我index.php

<html> 
<?php 

    include_once('connect.php'); 

    $sql = "SELECT * FROM data"; 
    $query = mysql_query($sql); 
    $result = array(); 


    while($row = mysql_fetch_array($query)) 
     array_push($result,     
      array(       
      'name' => $row[1],    
      'msg' => $row[2])); 

    echo json_encode(array("key" => $result));  
?> 

<body> 

<ul> 
    //insert fetch data here 
</ul> 



<script type="text/javascript" src="./js/jquery.js"></script> 
<script type="text/javascript" src="./js/custom.js"></script> 
</body> 
</html> 

,這裏是我的JQUERY

function my_function() { 
    $.getJSON("index.php", function(data) { 
     $.each(data.key, function(){ 
     $("ul").append("<li>Name: "+this['name']+"</li>" 
         "<li>message: "+this['msg']+ "</li>"); 
     }); 
}); 
} 
+1

如果你想有一個PHP腳本來返回JSON,那麼JSON字符串必須是唯一的** **的事情由腳本回聲。你有一堆html會導致無效的json。 –

+0

你在index.php中有srctag嗎?如果是這樣,那就是你的問題,讓它只返回json數組。如果沒有,請將帖子更新爲你有什麼 – Martijn

+0

你可以擴展更多關於你的意思的'必須是腳本' – bobbyjones

回答

0

第一個:檢查你自己的index.php輸出,看它是否顯示有效的json。 ¿是否有無效的UTF8字符?在這種情況下,json_encode的輸出爲空。

第二:我想使用純AJAX方法暗示JSON作爲數據類型:

jQuery.ajax({ 
     url: 'index.php', 
     dataType: 'json' 
}).done(function(data) { 
    for (i=1;i<data.length;i++) { 
     datarow=data[i]; 
      $("ul").append("<li>Name: "+datarow.name+"</li>"); 
      $("ul").append("<li>message: "+datarow.msg+ "</li>"); 
     } 

     }); 

第三:不使用相同的腳本來生成JSON和以顯示它,這都沒有如果你在前面做所有的事情,就可以將視圖與應用程序分開。在這種情況下,你可能會使用普通的php來生成所有的東西,就像之前的回答所說的那樣。 (@Abdoul Sy)

0

您不需要通過JSON獲取數據,因爲您在同一頁面上回顯JSON。 你可以做這樣的事情:

<ul id="jsonData" data-json-data="<?php echo json_encode($result;)?>" 

而在你的js文件:

var myData = $('#jsonData').data('json-data'); 
相關問題