【问题标题】:Connecting HTML, Javascript and PHP with Sessions使用会话连接 HTML、Javascript 和 PHP
【发布时间】:2016-06-10 10:10:34
【问题描述】:

我正在尝试使用 PHP、HTML 和 Javascript 为作业创建一个购物车,但我什至连基本的 PHP 工作都难以掌握。

由于这是一项作业,我不会发布我的确切代码,但我会发布一些修改过的代码来描述我正在努力解决的一般概念。另请注意,我在这篇文章中大大简化了程序,但我认为我已经包含了所有相关内容。

首先,我在 HTML 中有一个带有选择选项标签的表单:

<?php session_start(); ?> <!-- This is on the first line of the page -->
...
<form id="formexample" method="post" action="cart.php">
<select name="formexample2">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>
<select  name="formexample2">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>
<button type="button" onclick="addToCart()">Add to Cart</button>
</form>
<div class="test"></div>

"addToCart()" 是一个 Javascript 函数,我已将其写入一个单独的文件并导入到“header”标签中。我知道该功能有效,因为它会在我输入“alert("test");”时做出响应。其中一行如下:

$(".test").append("<?php include \"cart.php\"; ?>");

当我在“p”标签中用“test”替换附加时,它看起来没有问题。

“cart.php”是同一目录下的一个php文件。它存储会话的数据:

<?php   
$PHPtest= 1;


$_SESSION['cart'][$_POST['formexample1']] = $_POST['formexample1'];
    $_SESSION['cart'][$_POST['formexample1']][$_POST['formexample2']] = [$_POST['formexample2']] 

/* Note that in my actual code the form has 11 different select tags, some with up to ten options. I'm storing the information as a big multidimensional array in $_SESSION for ease. */

    ?>

我试图在我之前提到的同一个 Javascript 函数中创建一个循环,在其中我访问会话数据。循环以 "if(?php echo isset($_SESSION[\'cart\'][$_POST[\'formexample1\']]; ?>")" 开始 - 我在这里删除了问号之前的

$PHPtest = 1;

然后我把它写进了 Javascript 函数中:

var test = "<?php echo $PHPtest; ?>";
alert(test);

根据 Google 的说法,这是您在将 PHP 变量传递给 Javascript 时应该使用的格式。当我这样做时,警报只会准确显示引号之间的内容(即 )。

我一直在网上寻找,据我所知,我正在做人们所说的会话,将 PHP 变量分配给 Javascript 和数组;那么为什么它不起作用呢?

提前致谢。

编辑:

我暂时注释掉了 cart.php 中的 $_SESSION 行。我正在练习 $PHPtest。

cart.php 现在看起来像这样:

<?php   

session_start(); 
$PHPtest = 1;
echo json_encode($PHPtest);
?>

Javascript 函数现在看起来像这样(添加了 AJAX):

function addToCart()
{
var test;
    $.ajax(
    {
        url:"cart.php",
        type:"post",
        data:"$PHPtest",
        success:function(response) 
        {
            test = $.parseJSON(response);
            console.log(response); //sends the response to your console
        },
        error:function() 
        {
            console.log("Error");
        }
    });
    alert(test);
}

我还在主页顶部移动了“include "cart.php"”。请参阅 Josh S 的回复下的讨论,了解我是如何到达这里的。

警报显示“未定义”。

编辑 2 我在这里根据这个答案更新了我的函数:Get variable from PHP file using JQuery/AJAX

这就是我现在拥有的:

function addToCart()
{
    var test;
    $.ajax(
    {
        url:"cart.php",
        type:"post",
        data: data,
        success:function(PHPtest) 
        {
            test = $.parseJSON(PHPtest);
            console.log(test); //sends the response to your console
        },
        error:function() 
        {
            console.log("Error");
        }
    });
    alert(test);
}

我尝试了“PHPtest”和“test”的各种组合,但无法正常工作。现在我根本没有收到任何警报。

【问题讨论】:

  • 当你alert("&lt;?php echo $PHPtest; ?&gt;")时会发生什么?
  • 警报显示引号之间的确切内容,即显示尖括号、问号和其余部分。
  • 你在html页面的&lt;script&gt;标签中使用它吗?
  • Javascript 包含在“”中。然后,cart.php 被包含在一个带有 "$(".test").append("");" 的 Javascript 函数中。
  • 也许你应该使用load() 函数,就像这里的stackoverflow.com/questions/16933989/… - 所以...$(".test").load("path/to/cart.php");。也许它没有工作,因为 php 没有被正确加载。

标签: javascript php html session


【解决方案1】:

使用对 PHP 文件的 Ajax 调用来处理实时页面和 PHP。

PHP 在访问浏览器之前被处理。您不能即时使用它。

您不能在没有一点技巧的情况下混合使用前端和后端脚本(例如,AJAX 调用)。

编辑

如果使用 jQuery,并且你的脚本正在寻找一个帖子。

$.ajax({
    url:"script/location/run.php",
    type:"post",
    data:"name=value&your=post&data=goeshere",
    success:function(response) {
        console.log(response); //sends the response to your console
    },
    error:function() {
        console.log("um, error with the script, or it can't be found");
    }
});

编辑 2

购物车的设置应该与此类似;

<?php
session_start(); //On any PHP document (that are not includes or require) this is required at the top of the page to use sessions

$PHPtest= 1;


$_SESSION['cart']['formexample1'] = $_POST['formexample1'];
    $_SESSION['cart']['formexample2'] = $_POST['formexample2'] ;

/* Note that in my actual code the form has 11 different select tags, some with up to ten options. I'm storing the information as a big multidimensional array in $_SESSION for ease. */

?>

但是,如果您设置会话变量,您仍然无法在客户端(调用 AJAX 的浏览器)上使用 PHP 命令直接访问它们

因此您需要在此处回显您的购物车,以便您可以在客户端访问它们。

//at the end of cart.php
echo json_encode($_SESSION['cart']); //will convert your session cart to JSON and send to the response variable in your AJAX.

你的 JS

var cart = '';
$.ajax({
    url:"script/location/run.php",
    type:"post",
    data:"name=value&your=post&data=goeshere",
    success:function(response) {
        //response will hold the JSON value of your cart
        cart = $.parseJSON(response); //decodes to a JSON object in JavaScript;

        //you can access the cart variables like this
        console.log(cart.formexample1);

    },
    error:function() {
        console.log("um, error with the script, or it can't be found");
    }

【讨论】:

  • 谢谢。我现在正在阅读有关 AJAX 的信息。如果我还有任何问题,我会回来的。
  • 我已将 cart.php 的包含移动到文件的开头,并将 "if(isset($_POST)){...}" 添加到 cart.php 的开头避免错误。我想我需要使用 AJAX 函数来检索会话变量的值,但我不确定要使用哪一个 - 从我正在阅读的内容来看,我认为我需要使用“$.get()”?我正在阅读它(api.jquery.com/jquery.get)并且对参数感到困惑。 “url”显然是 .php 文件的名称(它在同一目录中),但我不知道在其他参数中添加什么。我不清楚这些例子。
  • 另外,请确保您的 ajax 正在调用的脚本在该页面上也有 session_start(),否则它将无法与您的会话交互。
  • 所以我将 "cart.php" 放在 url 之后,并在 "$_SESSION['cart'][$_POST['formexample1']][$_POST['formexample2']]" 之后“数据”?那是对的吗?我会将它存储在另一个变量中,例如“$variable = $.ajax({...});”吗?谢谢。
  • 哇哇哇.. 回到第一格哈哈。看来您不了解这些概念。 $_SESSION['cart'][$_POST['formexample1']] = $_POST['formexample1'];应该是 $_SESSION['cart']['formexample1'] = $_POST['formexample1'];您像分配多维数组一样分配 $_SESSION。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 2012-12-02
  • 1970-01-01
  • 2012-03-15
  • 2011-12-18
相关资源
最近更新 更多