将 HTML、Javascript 和 PHP 与 Sessions 连接起来


Connecting HTML, Javascript and PHP with Sessions

我正在尝试使用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''']]; ?>")"开头 - 我删除了这里问号前的<,这样你在我发表这篇文章时可以看到代码。这就是我的程序失败的地方。看来我的问题是将PHP变量传递给Javascript。为了测试这一点,我在购物车的开头写了以下内容.php:

$PHPtest = 1;

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

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

根据Google的说法,这是将PHP变量传递给Javascript时应该使用的格式。当我这样做时,警报只是准确地显示引号之间的内容(即<?php echo $cartCheck; ?>)。

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

提前谢谢。

编辑:

目前

,我已经注释掉了购物车中的 _SESSION 美元行.php。我正在和$PHPtest一起练习。

购物车.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);
}

我还在主页顶部移动了"包括"购物车.php"。请参阅Josh S回复下的讨论,看看我是如何到达这里的。

警报显示"未定义"。

编辑 2我在这里根据这个答案更新了我的函数:使用 JQuery/AJAX 从 PHP 文件中获取变量

这就是我现在拥有的:

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"的各种组合,但无法让它工作。现在我根本没有收到任何警报。

使用 Ajax 调用 PHP 文件来处理实时页面和 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");
    }