3

我有以下文件,这就是他们所做的:

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.phpoutput.php代码在需要时进行最小限度的更改

4

4 回答 4

2

基本上您当前的工作流程是:执行input.php一次 => 使用 JSoutput.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

希望这可以帮助。

于 2013-07-20T11:37:43.883 回答
1

那是因为你打过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
于 2013-07-20T08:55:53.620 回答
0

也许您的请求正在被缓存。尝试改变:

   $('#read').load('index.php?r='+ Math.floor((Math.random()*100)+1) +' #read');
于 2013-07-18T08:12:05.487 回答
0

将您的 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
}

索引.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>

刷新.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);
于 2013-07-20T10:26:30.607 回答