如何在收到jquery的帖子后刷新PHP页面并显示更改

How to refresh a PHP page and show changes after receiving post from jquery

本文关键字:PHP 刷新 显示 jquery      更新时间:2023-09-26

我有一个客户端jquery代码,它获取客户端的本地日期并将其发布到服务器。当服务器端收到这篇文章时,在我的PHP代码中,我想对页面进行一些更新(使用echo语句),并显示这些更改。那么,我如何才能强制那些echo语句更新那里的页面呢。

<?php 
.....
echo '<span style="color:yellow">Here it does echo fine!</span>';
if(isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0)
{
   echo '<span style="color:red">This doesn't show. What can I do to make it show?</span>';
}
.....
?> 

我这样做的原因是将信息从PHP传递到javascript。通过回显,我期望在HTML文档中写入一些内容,这样javascript就可以从更新后的HTML文档中提取信息。但是,既然这不太可能奏效,那么还有什么其他方法可以从PHP的if语句中向Javascript发送信息呢?

您可以通过动态创建表单并提交它来实现这一点:

$('body')
    .append('<form id="myForm"></form>'); //append a new form element with id myFormto <body>
$('#myForm') 
    .attr("action","#") .attr("method","post") //set the form attributes
    .append('<input type="hidden" name="dateStr" id="dateStr" value="!!YOUR VALUE HERE!!">') //add in all the needed input element
    .submit();

您不能直接从服务器端执行此操作。原因是您必须重新加载页面才能显示更改,但一旦重新加载页面,数据将不会被保留,除非您将更改保存到会话或cookie中。然后,在每次加载页面时,您都会检查会话变量或cookie是否存在,如果存在,则从会话或cookie加载数据,否则加载原始数据。

解决方案是使用Ajax。下面是一个简单的例子并加以说明。

PHP

if(isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0)
{
   echo "success";
}

Javascript:

$(function(){
  $('#button').on('click', function(e){
    e.preventDefault();
    $.ajax({
      url: 'yourphpcontroller.php',
      type: 'post',
      data: {dateStr: 'mystring' }, // can be obtained with jQuery attr
      success: function(data, status) {
        if(data == "success") { // the response coming from php; if the response is success means we can proceed
          $('#myhtmlelement').append('<span style="color:red"></span>'); // append to html tag          
        }
      },
      error: function(xhr, desc, err) {
        console.log(xhr);
        console.log("Details: " + desc + "'nError:" + err);
      }
    }); // end ajax call
  });