我有以下文件,它们就是这样做的:
input.php:从XML提要获取数据,连接到数据库并将其输入数据库。
output.php:连接到数据库并创建要输出的变量。
index.php:包括output.php
并使用变量输出数据。
refresh.js:Ajax刷新div以更新数据。
输入.php
$xml = simplexml_load_file( "http://domain.com/feed" );
$json = json_encode( $xml );
$array = json_decode( $json,TRUE );
$items = $array['channel']['item'];
$DB = new mysqli( 'localhost','USERNAME','PASSWORD','DATABASE' );
if( $DB->connect_errno ){
print "failed to connect to DB: {$DB->connect_error}";
exit( 1 );
}
$match = "#^(?:[^'?]*'?url=)(https?://)(?:m(?:obile)?'.)?(.*)$#ui";
$replace = '$1$2';
foreach( $items as $item ){
$title = $item['title'];
$url = preg_replace( $match,$replace,$item['link'] );
$title_url[] = array( $title,$url );
$sql_values[] = "('{$DB->real_escape_string( $title )}','{$DB->real_escape_string( $url )}')";
}
$SQL = "INSERT IGNORE INTO `read`(`title`,`url`) VALUES'n ".implode( "'n,",array_reverse( $sql_values ) );
if( $DB->query( $SQL ) ){
} else {
print "failed to INSERT: [{$DB->errno}] {$DB->error}";
}
$DB->set_charset( 'utf8' );
输出.php
$DB = new mysqli( 'localhost','USERNAME','PASSWORD','DATABASE' );
if( $DB->connect_errno ){
print "failed to connect to DB: {$DB->connect_error}";
exit( 1 );
}
$query = "SELECT `title`,`url` FROM `read` ORDER BY `order` DESC";
$result = $DB->query( $query );
// error-handling: make sure query returned a result
if( $result ){
while( $row = $result->fetch_array() ){
// list gets values from a numeric array
list( $title,$url ) = $row;
// using [] (append) is much faster than using array_push()
$data[] = array( 'title'=>$title,'url'=>$url );
}
$title = $data[0]['title'];
$url = $data[0]['url'];
}else{
//do something
}
索引.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Recently</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/refresh.js"></script>
</head>
<body>
<?php include_once "includes/output.php"; ?>
<p class="title"><span>Read </span>
<a id="read" href="<?php echo $url; ?>" target="_blank"><?php echo $title; ?></a>
</p>
</body>
</html>
刷新.js
var auto_refresh = setInterval(
function() {
$('#read').load('index.php #read');
}, 2000);
问题是,除非我刷新input.php
(这会破坏增量计数),否则数据不会插入数据库。我不知道为什么会发生这种事。有什么想法吗?
注意:因为我才刚刚开始学习更多关于PHP和数据库的知识,所以如果需要,我希望input.php
和output.php
代码的更改最小。
基本上,您当前的工作流程是:执行input.php
一次=>使用JS在一段时间内执行output.php
以获得输出。所以你可以看到问题是输入是静态的,而输出是动态的。
您可以单独修改刷新脚本:执行input.php
=>执行output.php
=>几秒钟后再次执行input.php
=>再次执行output.php
,依此类推:
var auto_refresh = setInterval(function() {
$.get('input.php', function () { // call input here
$('#read').load('index.php #read'); // call output here
});
}, 2000); // run again after 2 seconds, you might wanna make this number higher to offload i/o
希望这能有所帮助。
这是因为您调用了input.php
一次。
在您的index.php
中,没有任何地方可以再次调用它,因此output.php
被调用,它获取最新的行ORDER BY order DESC
,然后是$url = $data[0]['url']
。
您必须再次调用input.php
才能获得新数据。
您可以将refresh.js更改为以下内容:
(function refresh() {
$.get('input.php', function() {
$("#read").load("index.php", function() {
refresh();
});
});
})(); // self-executing anonymous functions are better than setInterval() to handle ajax
可能您的请求正在缓存中。尝试更改:
$('#read').load('index.php?r='+ Math.floor((Math.random()*100)+1) +' #read');
将input.php和output.php合并到一个文件中(例如io.php)。
// input.php content
// output.php content
// And instead of creating $title and $url variables use this
header('Content-type: application/json');
echo json_encode($data[0]);
不再需要在index.php中包含任何文件,只需编辑refresh.js,如下所示
setInterval(function(){ $.ajax({
url: 'io.php',
type: 'GET',
dataType: 'json',
cache: false,
success: function(m){
$('#read').text(m.title).attr('href',m.url);
}
}); }, 2000);
而且也不需要重新加载index.php。我认为这是更有效的方式
编辑:这是完整的代码
可能还有其他代码块需要在index.php中包含output.php,或者与我的方法相冲突。我不知道关于你们系统的其他信息。这只是一个建议。
io.php
(input.php+output.php)我不知道当这些文件组合在一起时,是否仍然需要保存在数据库中,但您可以在另一个页面中使用这些保存的数据
$xml = simplexml_load_file( "http://domain.com/feed" );
$json = json_encode( $xml );
$array = json_decode( $json,TRUE );
$items = $array['channel']['item'];
$DB = new mysqli( 'localhost','USERNAME','PASSWORD','DATABASE' );
if( $DB->connect_errno ){
print "failed to connect to DB: {$DB->connect_error}";
exit( 1 );
}
$match = "#^(?:[^'?]*'?url=)(https?://)(?:m(?:obile)?'.)?(.*)$#ui";
$replace = '$1$2';
foreach( $items as $item ){
$title = $item['title'];
$url = preg_replace( $match,$replace,$item['link'] );
$title_url[] = array( $title,$url );
$sql_values[] = "('{$DB->real_escape_string( $title )}','{$DB->real_escape_string( $url )}')";
}
$SQL = "INSERT IGNORE INTO `read`(`title`,`url`) VALUES'n ".implode( "'n,",array_reverse( $sql_values ) );
if( $DB->query( $SQL ) ){
} else {
print "failed to INSERT: [{$DB->errno}] {$DB->error}";
}
$DB->set_charset( 'utf8' );
$query = "SELECT `title`,`url` FROM `read` ORDER BY `order` DESC";
$result = $DB->query( $query );
// error-handling: make sure query returned a result
if( $result ){
while( $row = $result->fetch_array() ){
// list gets values from a numeric array
list( $title,$url ) = $row;
// using [] (append) is much faster than using array_push()
$data[] = array( 'title'=>$title,'url'=>$url );
}
header('Content-type: application/json');
echo json_encode($data[0]);
}else{
//do something
}
index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Recently</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/refresh.js"></script>
</head>
<body>
<p class="title"><span>Read </span>
<a id="read" href="" target="_blank"></a>
</p>
</body>
</html>
refresh.js
setInterval(function(){ $.ajax({
url: 'io.php',
type: 'GET',
dataType: 'json',
cache: false,
success: function(m){
$('#read').text(m.title).attr('href',m.url);
}
}); }, 2000);