[英]How to refresh a PHP page and show changes after receiving post from jquery
我有一个客户端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文档中提取信息。 但是,由于这不太可能起作用,因此从该if语句向Java脚本发送信息的其他方法有哪些?
您可以通过动态创建表单并提交来实现:
$('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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.