1

我试图从 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);给出解析器错误

警报(抛出错误);给出 SyntaxError: JSON.parse: 意外字符

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

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

4

1 回答 1

1

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

我所要做的就是删除一echo "hello"开始就会弄乱你的 JSON 的那个。

您可以在未来开发中使用的更多提示:

  • 不要使用alert('message'). 使用console.log('message'). console.log您可以在“开发者专区”中查看输出。在 chrome 中,您只需按 F12。我认为在 FF 中你需要安装 firebug 什么的。
  • output_stringin functionsuccess实际上是一个对象。
  • chrome 中的“开发者专区”还可以让您看到来自后端的响应。如果您使用过它,您可能会看到您的输出,hello{ "key":"value"}并立即注意到开头的讨厌的 hello。在http://wiki.mograbi.info/developers-tools-for-web-development了解更多信息
于 2013-10-17T11:22:51.247 回答