2013-02-21 71 views
1

我試圖從MySQL數據庫中讀取數據並將其傳遞給我的JavaScript文件。 我有很多在互聯網上搜索,並找到了不起作用的例子在我的情況。如何使用json PHP JQUERY Ajax從數據庫中讀取數據?

.html文件

<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> 
<html xmlns='http://www.w3.org/1999/xhtml'> 
<script language='JavaScript' type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script> 
<head> 
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' /> 
<title>Display Page</title> 
</head> 

<body> 
<button type='button' id='getdata'>Get Data.</button> 

<div id='result_table'> 

</div> 

<script type='text/javascript' language='javascript'> 

$(document).ready(function(){ 
$('#getdata').click(function(){ 
    alert("hello"); 
    $.ajax({ 
      url: 'db.php', 
      type:'POST', 
      dataType: 'json', 
      success: function(output_string){ 
        alert(output_string); 
       }, 
        error: function (xhr, ajaxOptions, thrownError){ 
        alert(xhr.statusText); 
        alert(thrownError); 
        } 
    }); 

}); 
}); 
</script> 
</body> 
</html> 

和PHP文件

<?php 
echo 'hello'; 
     $user = 'root'; 
     $pass = '123'; 
     $host = 'localhost'; 
     $db = 'internetProgrammeringProj'; 

     $connect = mysql_connect($host,$user,$pass); 
     $select = mysql_select_db($db,$connect); 

     $query = $_POST['query']; 
     $mysql_query = mysql_query("SELECT * FROM ratt "); 
     $temp = ""; 
     $i = 0; 
     while($row = mysql_fletch_assoc($mysql_query)){ 
      $temp = $row['id']; 
      $temp .= $row['namn']; 
      $temp .= $row['typ']; 
      $temp .= $row['url']; 
      $temp .= $row['forberedelse']; 

      $array[i] = $temp; 
      $i++; 
     } 



     echo json_encode($array); 
?> 

警報(xhr.statusText);給出解析錯誤

alert(thrownError);給出SyntaxError:JSON.parse:意外字符

螢火蟲不會在控制檯中顯示任何錯誤。

問題:我如何讓我的程序從數據庫中獲取內容並將其傳遞給json以在ajax中顯示警報?

+0

的'語法錯誤:JSON.parse:意外character'表明,jQuery的失敗,因爲它是解析響應文本JSON *不*有效的JSON。使用Firebug查看返回的文本是什麼,並在此處發佈。 – 2013-02-21 11:49:02

+0

檢查你的數組使用vat_dump來獲取它 – 2013-02-21 12:32:12

回答

1

我剛剛成功運行此代碼。

我所要做的就是在開始時刪除echo "hello",這會弄亂你的JSON。

一些更多的提示,你可以使用未來的發展:

  • 不要使用alert('message')。使用console.log('message')。您可以在「開發人員區域」查看console.log的輸出。在Chrome中,只需按F12。我認爲在FF中你需要安裝螢火蟲或其他東西。
  • output_string功能success實際上是一個對象。
  • chrome中的「開發人員區域」也可以讓你看到後端的響應。如果你已經使用它,你可能看到你的輸出是hello{ "key":"value"},並立即注意到在開始時討厭的問候。瞭解更多關於它在http://wiki.mograbi.info/developers-tools-for-web-development