【问题标题】:Update a php variable within the same page without reloading page在同一页面内更新 php 变量而不重新加载页面
【发布时间】:2015-09-22 13:12:55
【问题描述】:

我对 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 在刷新页面时丢失它的排序值。有人可以帮忙吗?

【问题讨论】:

    标签: javascript php jquery html ajax


    【解决方案1】:

    如果不重新加载并且不使用 ajax 之类的东西来调用 php 文件,就不可能更改 PHP 变量。

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

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

    示例 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 函数。

    【讨论】:

    • 谢谢你,我已经假设我只是不知道如何实施 Ajax 来解决我的问题。
    • 我更改了答案以包含示例解决方案。
    • 请随意将其标记为答案,以便人们知道它对您的帮助是正确的。
    猜你喜欢
    • 2011-04-08
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    相关资源
    最近更新 更多