在不重新加载页面的情况下更新同一页面中的php变量

时间:2015-09-22 13:12:56

标签: javascript php jquery html ajax

我对AJAX不是很了解,我很确定这是解决我的问题的方法。

我想在<TH> onclick上更新php变量。然后,该变量将用于使用Jquery表排序脚本对我的一些列进行排序。

在页面顶部(bodyshops.php)我有这个......

if (isset($_GET['sortStore'])) {
    $sortStore = $_GET['sortStore'];
}else{
    $sortStore = 'EMPTY';
}

在桌边我有这个......(我把$sortStore = 'X'作为例子)

<th style="text-align:left; cursor:pointer; background-color:#0a639d; color:#ffffff;" onclick="<?php $sortStore = '1' ?>"><?php echo $LANGT_Bodyshop_Name; ?></th>
<th style="cursor:pointer; background-color:#0a639d; color:#ffffff;" onclick="<?php $sortStore = '1' ?>">&nbsp;<?php echo $LANGT_Bodyshop_Contact; ?></th>
<th style="cursor:pointer; background-color:#0a639d; color:#ffffff;" onclick="<?php $sortStore = '2' ?>">&nbsp;<?php echo $LANGT_Bodyshop_Email; ?>&nbsp;</th>
<th style="cursor:pointer; background-color:#0a639d; color:#ffffff;" onclick="<?php $sortStore = '3' ?>">&nbsp;<?php echo $LANGT_Bodyshop_Phone; ?>&nbsp;</th>
<th style="cursor:pointer; background-color:#0a639d; color:#ffffff;" onclick="<?php $sortStore = '4' ?>">&nbsp;<?php echo $LANGT_Bodyshop_AddressPostcode; ?>&nbsp;</th>
<th style="cursor:pointer; background-color:#0a639d; color:#ffffff;" onclick="<?php $sortStore = '5' ?>">&nbsp;<?php echo $LANGT_Bodyshop_Capacity; ?>&nbsp;</th>
<th style="cursor:pointer; background-color:#0a639d; color:#ffffff;" onclick="<?php $sortStore = '6' ?>">&nbsp;<?php echo $LANGT_Bodyshop_CourtesyCars; ?>&nbsp;</th>

最终目标是能够编写一个if语句来决定运行什么jQuery脚本。

if ( $sortStore != 0 ) {
    // Run Function 1 
}else{
    // Run Function 2
}

这最终会帮助我在刷新页面时阻止TableSorter丢失它的排序值。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

无法在不重新加载的情况下更改PHP变量,并且无需使用类似ajax来调用php文件。

不可能的原因是PHP正在运行服务器端,如果没有重新加载,您只能更改客户端上的内容。如果可以在客户端上更改PHP变量,则会导致巨大的安全问题。

使用PHP代码更新页面只能通过向服务器发送新请求来完成,因此它可以执行PHP代码并发送回输出的任何内容。使用ajax你可以在后台制作这些请求,并因此“更改页面而不重新加载”,重新加载实际发生,但在后台只有前台页面的相关部分需要使用javascript更新。 / p>

示例ajax解决方案:

onclick :(将1替换为您要存储的值,或使用var替换

$.get("storeSort.php", {sort:1}, function(data){
    //nothing to be done. is just send
});

使用:

创建storeSort.php
<?php
// Start the session
session_start();

// Set session variables
$_SESSION["sort"] = $_GET['sort'];

在页面脚本中使用session_start()$_SESSION['sort']的值来确定要调用的jquery函数。