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中顯示警報?
的'語法錯誤:JSON.parse:意外character'表明,jQuery的失敗,因爲它是解析響應文本JSON *不*有效的JSON。使用Firebug查看返回的文本是什麼,並在此處發佈。 – 2013-02-21 11:49:02
檢查你的數組使用vat_dump來獲取它 – 2013-02-21 12:32:12