如何使用json PHP JQUERY Ajax从数据库中读取数据?

时间:2013-02-21 11:45:42

标签: javascript jquery ajax json

我试图从mysql数据库中读取数据并将其传递给我的javascript文件。 我在互联网上搜索了很多,并找到了在我的情况下无效的例子。

.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);给出parsererror

警报(thrownError);给出了SyntaxError:JSON.parse:意外字符

firebug在控制台中不显示任何错误。

问题:如何让我的程序从数据库中获取内容并使用json传递它以在ajax中显示警告?

1 个答案:

答案 0 :(得分:1)

我刚刚成功运行了这段代码。

我所要做的就是删除开头的echo "hello",这会弄乱你的JSON。

您可以将更多提示用于未来的开发:

  • 不要使用alert('message')。使用console.log('message')。您可以在&#34;开发人员区域&#34;中查看console.log的输出。在Chrome中,您只需按F12即可。我认为在FF你需要安装萤火虫或其他东西。
  • 函数output_string中的
  • success实际上是一个对象。
  • &#34;开发人员专区&#34;在chrome中还可以让您看到后端的响应。如果你已经使用它,你可能已经看到你的输出是hello{ "key":"value"}并立即注意到开头的令人讨厌的问候。在http://wiki.mograbi.info/developers-tools-for-web-development
  • 了解详情