我想从mysql获取数据,并通过json_encode
回显它,然后我的JQUERY
将通过$.getJSON
捕获JSON
并将结果附加到我的<ul>
中。
我试图弄清楚为什么 JQUERY 捕获的数据没有打印在我的索引上.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>");
});
});
}
您无需通过 JSON 获取数据,因为您在同一页面上回显 JSON。你可以做这样的事情:
<ul id="jsonData" data-json-data="<?php echo json_encode($result;)?>"
在您的 js 文件中:
var myData = $('#jsonData').data('json-data');
首先:检查你的索引.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西(