简体   繁体   English

如何使用 Ajax 提交更新 PHP 会话中存储的值

[英]How to make the value stored in the PHP session update with the Ajax submission

Use ajax to pass the value to the back-end, then put the passed value into the session in the back-end, and then use the value of the session in the front end.使用ajax把值传给后端,然后把传过来的值放到后端的session中,然后在前端使用session的值。 However, the session is only useful when it is submitted for the first time.但是,会话仅在首次提交时才有用。 No matter how many times the session is submitted later, the stored value is only the value of the first time.以后无论会话提交多少次,存储的值都只是第一次的值。

document.php :文档.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./js/jquery-3.6.0.js"></script>
</head>
<body>
    <select name="sreachmsg" id="sreachmsg">
        <option value="1">First thing</option>
        <option value="2">The second thing</option>
        <option value="3">The third thing</option>
        <option value="4">The fourth thing</option>
        <option value="5">The fifth thing</option>
    </select>
    <button id="sreach">search</button>
    <div id="session_val">
    <?php
        session_start();
        $rel = $_SESSION['rel'];
        include('conn.php');
        //取数据库数据
        $res = mysqli_query($conn,"SELECT * FROM test where id='$rel'");
        if($res){
            while($row = mysqli_fetch_assoc($res)){
    ?>
                <tr>
                    <td><?php echo $row["msg"] ?></td>
                </tr>
    <?php
            }
        }
    ?>
</div>
    <script>
        $(document).ready(function(){
            $("#sreach").click(function(){
                var param = $("#sreachmsg").val();
                $.ajax({
                    url: './ajax.php',
                    data: {param:param},
                    type: 'POST',
                    dataType: 'json',
                    success: function(e){
                        console.log(e);
                    }
                });
            });
        });
        
    </script>
</body>
</html>

ajax.php : ajax.php

<?php
$x=$_POST['param'];
header('Content-Type:application/json');
session_start();
$_SESSION['rel'] = $x;
 
$raw_date = array('code' => '1','msg' => $_SESSION['rel']);
 
$res_date = json_encode($raw_date);
echo $res_date;
?>

How to make the value stored in the session update with the submission?如何使 session 中存储的值随着提交的更新而更新?

When developing web apps you are working with two distinct, and separate, processing/rendering systems: one is on the server, and the other is on the client.在开发 Web 应用程序时,您正在使用两个不同且独立的处理/渲染系统:一个在服务器上,另一个在客户端上。 Each system processes different parts of the code, and have limited channels of communication between them.每个系统处理代码的不同部分,并且它们之间的通信渠道有限。

PHP is executed on the server (back-end). PHP 在服务器(后端)上执行。

HTML and Javascript are processed/rendered on the client (front-end/browser). HTML 和 Javascript 在客户端(前端/浏览器)上处理/呈现。

When the client, using a browser, calls for a page containing PHP, the PHP is first processed on the server then the resulting HTML code, CSS, Javascript, and text content is sent to the browser, as unrendered, unprocessed text.当客户端使用浏览器调用包含 PHP 的页面时,首先在服务器上处理 PHP,然后将生成的 HTML 代码、CSS、Javascript 和文本内容作为未渲染、未处理的文本发送到浏览器。 The browser then executes Javascript, renders CSS and HTML, and displays text.然后浏览器执行 Javascript,呈现 CSS 和 HTML,并显示文本。

Your Document file, document.php —containing PHP, HTML, and Javascript—when requested by the client, first gets processed by the PHP processor on the server where only the PHP is processed, and the PHP code is replaced with the results of that processing.您的 Document 文件document.php (包含 PHP、HTML 和 Javascript)在客户端请求时,首先由服务器上的 PHP 处理器处理,仅处理 PHP,然后 PHP 代码被替换为该结果的结果加工。 After that only HTML, Javascript, and text is sent to the browser.之后,只有HTML、Javascript 和文本被发送到浏览器。 No PHP code is sent to the front-end.没有 PHP 代码发送到前端。 What your browser receives does not contain PHP code and, therefore, cannot process the PHP code.您的浏览器接收到的内容不包含 PHP 代码,因此无法处理 PHP 代码。 Your browser does not "see" the PHP session variable $_SESSION['rel'] .您的浏览器没有“看到” PHP 会话变量$_SESSION['rel']

The document.php file would have to be reloaded in the browser, ie, re-requested from the server, in order for the PHP to execute on the server and the value of the PHP session variable to be returned to the browser and displayed in the div element in your HTML page. document.php文件必须在浏览器中重新加载,即从服务器重新请求,以便 PHP 在服务器上执行,并将 PHP 会话变量的值返回给浏览器并显示在HTML 页面中的div元素。

Since you're using XHR (Ajax), to send and receive data to and from the server, the HTML page, already loaded in the browser, is not reloaded—only the value of the PHP session variable, when the page was first called and the PHP was processed on the server, are displayed in the div element.由于您使用 XHR (Ajax) 向服务器发送数据和从服务器接收数据,因此不会重新加载已经加载到浏览器中的 HTML 页面——只有 PHP 会话变量的值,当页面第一次被调用时并且 PHP 在服务器上进行了处理,都显示在div元素中。 (For this reason it appears to you the PHP session variable is not getting updated, but it actually is. If you open your browser console you'll see the data returned to the ajax call is the same as the form data sent to the server, and the updated server-side PHP session variable.) (因此,在您看来 PHP 会话变量没有更新,但实际上是更新了。如果您打开浏览器控制台,您会看到返回到 ajax 调用的数据与发送到服务器的表单数据相同,以及更新的服务器端 PHP 会话变量。)

Your document.php as rendered in the browser, without reloading, successfully posts your form data to to your ajax.php file on the server.您在浏览器中呈现的document.php无需重新加载即可成功将表单数据发布到服务器上的ajax.php文件。 The PHP in this file is processed on the server and a JSON response is returned, still without reloading, to the HTML page's ajax call.此文件中的 PHP 在服务器上进行处理,并返回一个 JSON 响应,但仍不重新加载,给 HTML 页面的 ajax 调用。

Since you're not reloading your page in the browser you must use Javascript to process and display this response in your HTML div tag.由于您没有在浏览器中重新加载页面,因此您必须使用 Javascript 来处理并在 HTML div标记中显示此响应。

You have two options:你有两个选择:

  1. Put all the PHP code in the main HTML document and reload it by POST'ing the form data back to itself.将所有 PHP 代码放在主 HTML 文档中,并通过将表单数据 POST 回自身来重新加载它。 In this case don't use Javascript/XHR/Ajax, or...在这种情况下,不要使用 Javascript/XHR/Ajax,或者...

  2. Move all your PHP code to ajax.php and use only XHR (Ajax) and Javascript to retrieve data from the server and update the HTML file.将所有 PHP 代码移至ajax.php并仅使用 XHR (Ajax) 和 Javascript 从服务器检索数据并更新 HTML 文件。


OPTION 1选项1

document.php文件.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="document.php" method="post">
        <select name="searchmsg">
            <option value="1">First thing</option>
            <option value="2">The second thing</option>
            <option value="3">The third thing</option>
            <option value="4">The fourth thing</option>
            <option value="5">The fifth thing</option>
        </select>
        <input type="submit" value="search">
    </form>
    <div>
        <table>
<?php
    session_start();
    $_SESSION['rel'] = (isset($_POST['searchmsg']))? $_POST['searchmsg']: 0;
    $rel = $_SESSION['rel'];
    include('conn.php');
    //取数据库数据
    $query = sprintf(
        "SELECT * FROM test where id='%s'",
        mysqli_real_escape_string($mysqli, $rel)
    );
    $res = mysqli_query($conn, $query);
    if($res){
        while($row = mysqli_fetch_assoc($res)){
?>
                <tr>
                    <td><?php echo $row["msg"] ?></td>
                </tr>
<?php
        }
    }
?>
    </table>
</div>
</body>
</html>

OPTION 2选项 2

document.html文档.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./js/jquery-3.6.0.js"></script>
</head>
<body>
    <select name="searchmsg" id="searchmsg">
        <option value="1">First thing</option>
        <option value="2">The second thing</option>
        <option value="3">The third thing</option>
        <option value="4">The fourth thing</option>
        <option value="5">The fifth thing</option>
    </select>
    <button id="search">search</button>
    <div id="searchdiv">
      <table>
          <tr>
              <td>make selection to search</td>
          </tr>
      </table>
   </div>
    <script>
        $(document).ready(function(){
            $("#sreach").click(function(){
                var param = $("#searchmsg").val();
                $.ajax({
                    url: './ajax.php',
                    data: {param:param},
                    type: 'POST',
                    dataType: 'json',
                    success: function(e){
                        console.log(e);
                        table = document.querySelector('#searchdiv table');
                        table.innerHTML = '';
                        $.each(e, function(i, item){
                            var row = table.insertRow();
                            var cell = row.insertCell();
                            cell.innerHTML = item.msg;
                        });

                    }
                });
            });
        });
        
    </script>
</body>
</html>

ajax.php ajax.php

$x=$_POST['param'];
header('Content-Type:application/json');
session_start();
$_SESSION['rel'] = $x;
 
$rel = $_SESSION['rel'];
include('conn.php');
//取数据库数据
$query = sprintf(
    "SELECT * FROM test where id='%s'",
    mysqli_real_escape_string($mysqli, $rel)
);
$res = mysqli_query($conn, $query);
$raw_date = array();
if($res){
    while($row = mysqli_fetch_assoc($res)){
        $raw_date[] = array('code' => $row['code'],'msg' => $row['msg']);
    }
}
 
$res_date = json_encode($raw_date);
echo $res_date;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM