我试图理解 .ajax() 函数与 jQuery 的魔力。我很难做我想做的事。我基本上想要一个内容每 x 次(大约每 10 秒)刷新一次的 div。主要是,这将输出已发布到我的数据库中的表中的最新帖子。我几乎用这个例子来了解如何实现我的目标,但不幸的是我没有得到我想要的。
我正在尝试设置我的文件,以便当单击刷新按钮时,div 会刷新并显示最新的帖子。
一方面我们有index.php 文件:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>Test page</title>
</head>
<body>
<h1>Welcome to the form</h1>
<h2>We are going to try to process this with AJAX</h2>
<h3>I hope it works!</h3>
<div id="content"></div>
<button id="refresh>Refresh!</button>
<script type="text/javascript">
$('#refresh').on('click', function(){
$.ajax({
type: "POST",
url: "process.php",
data: ,
error: function(data){
$('#content').text('Update unsuccessful!').
slideDown('slow');
console.log(data);
},
success: function(data){
$('#content').text('Update completed!');
console.log(data);
//somewhere over here use the $.getJSON() function
},
complete: function(data){
setTimeout(function(){
$('#content').slideUp('slow');
}, 3000);
}
});
});
</script>
</body>
</html>
另一方面,我们有 process.php 文件从数据库查询结果:
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "root";
$db = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sth = $db->query("SELECT * FROM posts");
$sth->setFetchMode(PDO::FETCH_ASSOC);
echo json_encode($sth);
您知道如何实现这一目标吗?
为了构建我的结果,我想在 jQuery 代码的成功部分中使用类似的内容:
$('#outputdiv').html(
//html code here fetching the JSON data to appear within custom divs (so I can apply css styles to them)
);
另外,您知道如何自动化 div 以每次使用相同的 &.ajax() 函数带来新结果吗?我已经通读了文档并遵循了很多示例,但我仍然无法得到我想要的!
提前致谢!
干杯!
<小时/>编辑: -修复了echo json_encode,“process.php”,删除了data:行,并将传递(数据)放入success: error:和complete:区域,但仍然不起作用
最佳答案
第一个 url 应该是字符串类型,所以它看起来像这样
url: "process.php",
然后在 process.php
文件中回显您的结果,如下所示
echo json_encode($sth);
在您的错误中,成功函数添加了这样的参数
error: function(data){
//your code
},
success: function(data){
//your code
}
根据您的代码,也不需要您的变量form_data
。所以删除这一行
data: form_data,
关于php - 使用 jQuery 的 $.ajax( ) 函数从 php 文件中获取 JSON 数据不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21745465/