简体   繁体   English

自动更新另一个页面而无需刷新

[英]Automatically update another page without refreshing

I have this problem on how I could automatically update my webpage without refreshing. 我在不刷新的情况下如何自动更新网页存在问题。 Could someone suggest and explain to me what would be the best way to solve my problem? 有人可以向我建议和解释什么是解决我的问题的最佳方法吗? Thanks in advance 提前致谢

add.php file In this php file, I will just ask for the name of the user. add.php文件在此php文件中,我只要求输入用户名。

 <form id="form1" name="form1" method="post" action="save.php">
      <input type="text" name="firstname" id="firstname"/>
      <input type="text" name="lastname" id="lastname"/>
      <input type="submit" name="add" id="add" value="add"/>
 </form>

save.php In this file, I will just save the value into the database. save.php在此文件中,我将把值保存到数据库中。

  $firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
  $lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';

  $sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
  $sql=$db->prepare($sql);
  $sql->execute();

studentlist.php In this file, i want to display the name I enter studentlist.php在此文件中,我想显示输入的名称

  $sql="Select firstname, lastname from student";
  $sql=$db->prepare($sql);
  $sql->execute();
  $output="The List of students <br></br>";

  while($result=$sql->fetch(PDO::FETCH_ASSOC))
  {
   $output.="".$result['firstname']." ".$result['lastname']."<br></br>";
  }

Problem When the two pages is open, I need to refresh the studentlist.php before i can see the recently added data. 问题打开两个页面时,我需要刷新Studentlist.php才能看到最近添加的数据。

thanks :D 感谢:D

You'll want to use ajax and jquery. 您将要使用ajax和jquery。 Something like this should work: 这样的事情应该起作用:

add.php add.php

add to the head of the document: 添加到文档的开头:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){//loads the information when the page loads
  var saveThenLoad = {
        url: "save.php",//the file sending data to
        type:      'POST',//sends the form data in a post to save.php
        dataType: 'json',   
        success : function(j) {
            if(j.error = 0){
               $("#student_info").html(j.info);//this will update the div below with the returned information
            } else {
               $("#student_info").html(j.msg);//this will update the div below with the returned information
            }
        }
    }
//grabs the save.submit call and sends to the ajaxSubmit saveThenLoad variable    
  $("#save").submit(function() {
    $(this).ajaxSubmit(saveThenLoad); 
     return false;
  });   
//grabs the submit event from the form and tells it where to go. In this case it sends to #save.submit above to call the ajaxSubmit function
  $("#add").click(function() {      
    $("#save").submit();
  });
});
</script>

<!-- put this in the body of the page. It will wait for the jquery call to fill the data-->
<div id="student_info">
</div>

I would combine save and studentlist into one file like this: 我将把savestudentlist合并到一个文件中,如下所示:

$return['error']=0;
$return['msg']='';
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';

$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
if(!$sql->execute()){
  $return['error']=1;
  $return['msg']='Error saving data';
}

$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
if(!$sql->execute()){
  $return['error']=1;
  $return['msg']='Error retrieving data';
}
$output="The List of students <br></br>";

while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
   $output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
$return['$output'];
echo json_encode($return);

Does this need to be in three separate files? 是否需要在三个单独的文件中? At the very least, could you combine add.php and studentlist.php? 至少,您可以将add.php和studentlist.php结合起来吗? If so, then jQuery is probably the way to go. 如果是这样,那么jQuery可能就是要走的路。 You might also want to use some html tags that would make it easier to dynamically add elements to the DOM. 您可能还希望使用一些html标记,以使向DOM动态添加元素变得更加容易。

Here's the combined files: 这是合并的文件:

<form id="form1" name="form1">
      <input type="text" name="firstname" id="firstname"/>
      <input type="text" name="lastname" id="lastname"/>
      <input type="submit" name="add" id="add" value="add"/>
 </form>
  The List of students <br></br>
  <ul id="student-list">

<?php
 //I assume you're connecting to the db somehow here
  $sql="Select firstname, lastname from student";
  $sql=$db->prepare($sql);
  $sql->execute();
  while($result=$sql->fetch(PDO::FETCH_NUM)) //this might be easier to output than an associative array
  {
  //Returns will make your page easier to debug
   print "<li>" . implode(" ", $result) . "</li>\n"; 
  }
?>
  </ul>

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
    $('#form1').submit(function(event){
        event.preventDefault();
        //submit the form values
        var firstname = $('#firstname').val(); 
        var lastname = $('#lastname').val();
        //post them
        $.post( "test.php", { firstname: firstname, lastname: lastname })
           .done( function(data) {
        //add those values to the end of the list you printed above
               $("<li>" + firstname + ' ' + lastname + "</li>").appendTo('#student-list');                  
           });
        });
    });
</script>

You might want to do some testing in in the $.post call above to make sure it was handled properly. 您可能需要在上面的$ .post调用中进行一些测试,以确保对其进行了正确处理。 Read more about that in the docs . docs中阅读有关此内容的更多信息。

If you really need three files, then you'll might need to use ajax to do some sort of polling on studentlist.php using setTimeout to see if you have any new items. 如果您确实需要三个文件,则可能需要使用ajax使用setTimeout对studentlist.php进行某种轮询,以查看是否有任何新项目。

The cheap-way is using a meta-refresh to refresh your page (or use JavaScript setInterval and ajax). 便宜的方法是使用元刷新来刷新页面(或使用JavaScript setInterval和ajax)。

The more expensive way is having a Realtime JavaScript application. 较昂贵的方法是拥有Realtime JavaScript应用程序。 Look at Socket.IO or something like that. 看一下Socket.IO或类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM