【问题标题】:Send JS variable to PHP on another page without form将 JS 变量发送到另一个页面上的 PHP 没有表单
【发布时间】:2021-09-20 17:42:40
【问题描述】:

我有一个带有搜索字段的 html 页面,该页面可以输入一个名称,其中返回一个名称和 ID 表(特别是来自 Steam)。最左边的列,名称,是我想要的超链接,当点击时,将用户带到所述玩家的个人资料(profile.php),我想在名称时将“名称”和“steamid”发送到该 profile.php链接被点击,所以本质上是从一个页面发送两个 JS 变量到另一个页面的 PHP 后端。

我是 ajax 的新手,似乎这是使用它的唯一方法,所以在研究了一段时间后,这就是我的想法:

$(document).ready(function() {

        $('#playerList td').click(function(e) {
            if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
                console.log($(this).text());

                var name = $(this).text();
                var steamid = $(this).closest('tr').children('td:nth-child(2)').text();

                $.ajax({
                  url: 'profile.php',
                  method: 'POST',
                  data: {
                        playersSteamID : steamid,
                        playersName : name 
                  },
                  success: function() {
                    console.log('success');
                  },
                  error: function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest);
                    console.log(textStatus);
                    console.log(errorThrown);
                  }
                })
            }
        });
        
    });

ajax 定义的一切都按我的意愿工作,我想将“name”和“steamid”变量发送到 profile.php,但我认为我不了解 ajax 的工作原理。我的理解是ajax可以将信息(通常是我所看到的json对象)“发布”到url,但也可以从页面返回信息?这就是我有点困惑的地方,我想知道我是不是用错了。

快速说明:playerList 是我的桌子的 ID。

当我单击超链接时,它会将我带到 profile.php,这正是我想要的,但 php 的 $_POST[] 数组似乎为空/null,因为我在尝试访问时收到“未定义的数组键”错误“playersSteamID”和“playersName”。 var_dump() 也返回 NULL,所以我想知道在 ajax 中发送 data{} 字段的方式是否存在问题。我对此仍然很陌生,因此非常感谢任何帮助。

更新:我如何访问 profile.php 中的变量

<?php
    echo var_dump($_POST['playersName']);
    echo var_dump($_POST['playersSteamID']);

    if (isset($_POST['playersName'])) {
        console_log("PLAYER_NAME => ".$_POST['playersName']);
    }
    if (isset($_POST['playersSteamID'])) {
        console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
    }
?>

profile.php 的其余部分正在获取这些变量并运行几个 sql 查询并构建一个在给定适当变量的情况下工作的表,但由于 $_POST[] 是空的,我无法继续上述点作为前两个行返回 null 并且条件永远不会为真,因为 isset() 为假。

【问题讨论】:

  • 控制台日志名称和 steamid,也使用引号作为数据中的变量名称,例如 data { "playersSteamID":steamid, "playersName": name}
  • 您好,我刚刚在 ajax 调用之前记录了“name”和“steamid”vars,它们应该是它们应该是的,但是在 data{} 块中添加引号似乎没有任何变化。
  • 分享profile.php代码
  • 所以您点击的是单元格中的链接?
  • 对了,表格是两列,最左边的一个链接,点击最左边的时候,我想把那行的两个变量发送到profile.php

标签: javascript php html jquery ajax


【解决方案1】:

ajax 用于,postget 参数/信息从/到 URL,而不重定向/刷新/导航到特定页面。

请记下不要重定向/刷新/导航

在您的情况下,您想将 2 个参数发送到 profile.php 并且您还想导航到它,是的..?但是为此您使用的是 Ajax,这不是一个正确的选择。

解决方案:-

-> 使用普通的表单提交方式,并将参数发布到profile.php,在这种情况下,您将被重定向到 profile.php 并可以期待正常的功能。

您可以使用带有提交按钮的普通表单{pretty normal},或使用自定义函数提交表单,如果需要完成一些进一步的工作{表单验证}。

你的函数看起来像这样......

$(document).ready(function() {

        $('#playerList td').click(function(e) {
            e.preventDefault();
            if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
                console.log($(this).text());

                var name = $(this).text();
                var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
               //Do some other stuffs
               document.forms['someform'].submit();//submitting the form here
            }
        });
    });

profile.php 中的其余部分保持不变。

->如果你真的想使用ajax,请关注。

Ajax 用于动态网页设计,在不刷新页面的情况下从服务器获取数据非常有用。

您应该更改您在profile.php 文件中的回复方式。

例如:-

<?php
if(isset($_POST['playersSteamID'])){
   $name = $_POST['playersName'];
   $id = $_POST['playersSteamID'];
   //Do your stuff here db query whatever
   //Here echo out the needed html/json response.
   echo "<h3>".$name."</h3>";
   echo "<h4>".$playersSteamID."</h4>";
}
?>

响应{来自:echo} 将在 function(data)data 中可用,在 ajax 成功时,您可以在任何您想要的任何地方使用这个 data

例如:-

success: function(data){
         console.log(data);//for debugging
         $('#mydiv').html(data);//appending the response.
         }

-> 使用 php 会话并将 steamID 存储在 sesssion 变量中,如果您的网站中有一些登录功能,这将非常有用。

$_SESSION['steamID'] = //the steamID here;

这个变量可以在站点使用的任何地方通过在页面中调用session_start()来使用,你要使用会话。

例如:-

<a href="profile.php" target="_self"> click here to view your profile </a>

profile.php

<?php
    session_start();
    $id = $_SESSION['steamID'];
    //echo var_dump($_POST['playersName']);
    //echo var_dump($_POST['playersSteamID']);

    /*if (isset($_POST['playersName'])) {
        console_log("PLAYER_NAME => ".$_POST['playersName']);
    }
    if (isset($_POST['playersSteamID'])) {
        console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
    }*/
    echo $id;
    //Do your work here......
?>

如有任何疑问,请发表评论。

【讨论】:

    【解决方案2】:

    超链接可能会导致您不想要的页面导航。
    页面导航将发出一个 get 请求,但您的端点期待一个 post 请求。
    您可以通过将 href 设置为 # 或完全删除 &lt;a&gt; 来停止导航。
    您也可以尝试在事件对象上调用preventDefault

    $(document).ready(function() {
    
            $('#playerList td').click(function(e) {
                e.preventDefault();
                if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
                    console.log($(this).text());
    
                    var name = $(this).text();
                    var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
    
                    $.ajax({
                      url: 'profile.php',
                      method: 'POST',
                      data: {
                            playersSteamID : steamid,
                            playersName : name 
                      },
                      success: function(data) {
                        console.log('success', data);
                      },
                      error: function(XMLHttpRequest, textStatus, errorThrown) {
                        console.log(XMLHttpRequest);
                        console.log(textStatus);
                        console.log(errorThrown);
                      }
                    })
                }
            });
            
        });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-05
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多