【问题标题】:How to continuously update a part of the page如何不断更新页面的一部分
【发布时间】:2012-05-16 13:28:33
【问题描述】:

http://pastebin.com/dttyN3L6

处理表单的文件叫做upload.php

我从未真正使用过 jquery/js,所以我不确定我将如何执行此操作或将代码放在哪里。

和这个setInterval (loadLog, 2500);有关

另外,我怎样才能让用户在不刷新页面的情况下提交表单?

 $.ajax({  
  type: "POST",  
  url: "upload.php",  
  data: dataString,  
  success: function() {  

  }  
});  
return false;  `

 <?php 
 $conn1 = mysqli_connect('xxx') or die('Error connecting to MySQL server.');
 $sql = "SELECT * from text ORDER BY id DESC LIMIT 1";
 $result = mysqli_query($conn1, $sql) or die('Error querying database.');
 while ($row = mysqli_fetch_array($result)) {
      echo  '<p>' . $row['words'] . '</p>';
 }
 mysqli_close($conn1);

 ?>

 </div>

 <?php     
 if (!isset($_SESSION["user_id"])) {

 } else {
      require_once('form.php'); 
 }

 ?>

【问题讨论】:

  • 那个 pastebin 缩进是怎么回事?您可以在这里发布您的代码吗?
  • 研究PeriodicalUpdater jQuery插件。

标签: php javascript jquery forms


【解决方案1】:

这很简单。 要使用 Jquery 访问元素,请使用 css 选择器,例如,要获取名称为“foo”的输入字段的值,请执行以下操作:

var fooVal = $("input[name=foo]").val();

要将其发送到服务器,您需要将事件侦听器(例如,单击)附加到提交按钮/任何其他元素

var data = { varName : fooVal };
var url = "http://example.com";
var responseDataType = "json";
function parseResponse(JSON)
{
   // your code handling server response here, it's called asynchronously, so you might want to add some indicator for the user, that your request is being processed
}

$("input[type=submit]").on('click', function(e){
  e.preventDefault();
    $(this).val("query processing");
    $.post(url,data, parseResponse, responseDataType);
 return false;
});

如果您想进行持续更新,当然可以添加计时器或其他一些逻辑。但我希望您了解如何处理此类案件;

【讨论】:

    【解决方案2】:

    您可以在不刷新页面的情况下提交表单,如下所示:

    form.php:

    <form action='profile.php' method='post' class='ajaxform'>
     <input type='text' name='txt' value='Test Text'>
     <input type='submit' value='submit'>
    </form>
    
    <div id='result'>Result comes here..</div>
    

    profile.php:

    <?php
          // All form data is in $_POST
    
          // Now perform actions on form data here and 
          // create an result array something like this
          $arr = array( 'result' => 'This is my result' );
          echo json_encode( $arr );
    ?>
    

    jQuery:

    jQuery(document).ready(function(){
    
        jQuery('.ajaxform').submit( function() {
    
            $.ajax({
                url     : $(this).attr('action'),
                type    : $(this).attr('method'),
                dataType: 'json',
                data    : $(this).serialize(),
                success : function( data ) {
                            // loop to set the result(value)
                            // in required div(key)
                            for(var id in data) {
                                jQuery('#' + id).html( data[id] );
                            }
                          }
            });
    
            return false;
        });
    
    });
    

    如果您想在特定时间后调用 ajax 请求而不刷新页面,您可以尝试以下操作:

    var timer, delay = 300000;
    
    timer = setInterval(function(){
        $.ajax({
          type    : 'POST',
          url     : 'profile.php',
          dataType: 'json',
          data    : $('.ajaxform').serialize(),
          success : function(data){
                      for(var id in data) {
                        jQuery('#' + id).html( data[id] );
                      }
                    }
        });
    }, delay);
    

    您可以像这样随时停止计时器:

    clearInterval( timer );
    

    希望这会给你一个完成任务的方向。

    【讨论】:

    • 您应该使用 jQuery 的 $.each() 方法,而不是使用 for(index in array)。我倾向于认为,如果你包含一个库,你应该充分利用它,而不是混搭。
    【解决方案3】:

    要回答您的部分问题,您可以使用 ajax。

    <html><head></head><body>
    <div id="feed"></div>
    <script type="text/javascript">
    var refreshtime=10;
    function tc()
    {
    asyncAjax("GET","upload.php",Math.random(),display,{});
    setTimeout(tc,refreshtime);
    }
    function display(xhr,cdat)
    {
     if(xhr.readyState==4 && xhr.status==200)
     {
       document.getElementById("feed").innerHTML=xhr.responseText;
     }
    }
    function asyncAjax(method,url,qs,callback,callbackData)
    {
        var xmlhttp=new XMLHttpRequest();
        //xmlhttp.cdat=callbackData;
        if(method=="GET")
        {
            url+="?"+qs;
        }
        var cb=callback;
        callback=function()
        {
            var xhr=xmlhttp;
            //xhr.cdat=callbackData;
            var cdat2=callbackData;
            cb(xhr,cdat2);
            return;
        }
        xmlhttp.open(method,url,true);
        xmlhttp.onreadystatechange=callback;
        if(method=="POST"){
                xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xmlhttp.send(qs);
        }
        else
        {
                xmlhttp.send(null);
        }
    }
    tc();
    </script>
    </body></html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 2021-12-17
      • 2012-09-12
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多