AJAX / LocalStorage:是否可以将JS变量传递给PHP?

时间:2021-03-07 00:06:21

I was wondering, what'd be the best way to store a shopping cart?
I thought about storing products ID's in localstorage/sessionstorage and then use AJAX to retrieve the products from the server.
The only problem is that I don't know how to pass the items from the localstorage to PHP...
I'm guessing it's probably not possible directly, and I thought about a form though I have no idea how to implent it...
The idea is that when a user clicks "Add to cart" the item id and quantity is added to the localstorage, and when a user views his cart, the item details (image, name, price...) are being retreived from the database. I'm probably going to use this tutorial
http://verido.dk/index.php/ressourcer/artikler/loading-and-saving-data-dynamically-using-php-jquery-and-mysql/

我想知道,什么是存放购物车的最佳方式?我考虑过将产品ID存储在localstorage / sessionstorage中,然后使用AJAX从服务器中检索产品。唯一的问题是我不知道如何将项目从localstorage传递给PHP ...我猜它可能不是直接的,我想到了一个表单虽然我不知道如何实现它..这个想法是当用户点击“添加到购物车”时,项目ID和数量被添加到localstorage,当用户查看他的购物车时,项目详细信息(图像,名称,价格......)正在从数据库。我可能会使用这个教程http://verido.dk/index.php/ressourcer/artikler/loading-and-saving-data-dynamically-using-php-jquery-and-mysql/

I could as well give up on local storage and go with sessions and database but I'd really like to give users that dynamic web experience.

我还可以放弃本地存储并使用会话和数据库,但我真的很想给用户带来动态的网络体验。

Another possible way I just came up with is to use URLs like file.php?prodid=......, although URLs like this may get way too long.

我想出的另一种可能的方法是使用像file.php?prodid = ......这样的URL,尽管这样的URL可能会太长。

Thanks in advance!

提前致谢!

4 个解决方案

#1


4  

'You must remember that Server-Side (PHP) code is read before it converts the code to browser-side code. JavaScript is manipulated browser-side...

'你必须记住,在将代码转换为浏览器端代码之前,会读取服务器端(PHP)代码。 JavaScript被操纵浏览器端...

So one-dimensionally, you cannot pass JavaScript to PHP.

所以一维地说,你不能将JavaScript传递给PHP。

However...

然而...

With Ajax and in your case I suggest JSON you can send JavaScript data to a PHP page and bring the response back to your JavaScript methods. I think this will suit your needs. I can provide a simple example if you want.

使用Ajax,在您的情况下,我建议JSON您可以将JavaScript数据发送到PHP页面并将响应带回JavaScript方法。我认为这符合您的需求。如果你愿意,我可以提供一个简单的例子。

//--example below:

// - 以下示例:

JavaScript:

JavaScript的:

//Ajax Method
function processAjax(queryString, processDiv, responseDiv) {

responseDiv.innerHTML = '';
var myAjax;
try {
    // Modern Browsers-->
    myAjax =new XMLHttpRequest();
} catch (e) {
    // antique ie browsers-->
    try {
        myAjax =new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            myAjax =new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            // Something went wrong
            document.getElementById('processDiv').innerHTML="";
            alert("Your browser malfunctioned!  Please try again. Consider installing a modern browser if the problem persists.");
            return false;
        }
    }
}
myAjax.onreadystatechange = function() {
    if (myAjax.readyState == 4) {
        var ajaxResponse = myAjax.responseText;
                responseDiv.innerHTML = ajaxResponse;
        processDiv.innerHTML = "";

                    //NOTE: HERE IS WHERE AJAX IS FINISHED, SO IF YOU WANT TO DO SOMETHING ELSE HERE YOU CAN!
                    //POST PROCESSING----->
                    // IE: alert('I am finished processing now!');
                    // or call another function:
                    // anotherFunction();

            } else {
        processDiv.innerHTML = '<img src="http://www.mysite.com/images/loadingicon.gif" alt="processing....." />';
    }
}
myAjax.open("GET", queryString, true);
myAjax.send(null);

}


function sendStorage() {

   var helloVar = 'Hello, I am passed to PHP #1';
   var worldVar = 'I am the second value passed to PHP!';
   var processId = 'process_div';
   var resultId = 'result_div';
   var queryString = 'http://www.mysite.com/process.php?hello=' + helloVar + '&world=' + worldVar;

   processAjax(queryString, processId, resultId);

}

Now for some HTML:

现在有些HTML:

<div id="content">
       <div id="process_div"> This is where processing will occur </div>
       <div id="result_div"> This is where my response will display </div>
</div>

Now for a process.php (NOTE: FOR SECURITY, I STRONGLY SUGGEST YOU DON'T REVEAL A SERVER-SIDE PROCESSING PAGE IN YOUR JAVASCRIPT)

现在为process.php(注意:为安全起见,我强烈建议您不要在您的JAVASCRIPT中显示服务器端处理页面)

<?php

  //init
  $hello = '';
  $world = '';
  $errors = 0;

  //set
  //Security note: never trust a URL request.. you should clean all $_GET, $_REQUEST, AND $_POST with the PHP htmlspecialchars() method (take a look at php.net for that)
  (isset($_GET['hello'])) ? $hello = $_GET['hello'] : $errors++;
  (isset($_GET['world'])) ? $world = $_GET['world'] : $errors++;

  //process
  if($errors > 0) {
      echo 'Errors Detected! Missing querystring get data!';
  } else {
      echo '<p>Hello received: ' . $hello . '</p>';
      echo '<p>World received: ' . $world . '</p>';
      //now we can process $hello and $world server side!
  }

?>

?>

Important: you should really look into learning some JSON and $_POST requests as they are more secure, faster and you can easily manipulate returned data. I suggest looking at a library like jquery for simplified examples.

重要提示:您应该学习一些JSON和$ _POST请求,因为它们更安全,更快,您可以轻松地操作返回的数据。我建议查看像jquery这样的库来简化示例。

I have not tested this code, but it should work.. Let me know if you have questions or this does not answer your question.

我没有测试过这段代码,但它应该可以工作..如果您有疑问或者这不能回答您的问题,请告诉我。

Glad to help!

乐意效劳!

#2


2  

Use AJAX to send data to the server (GET or POST) and store these values in a session variable or cookie on the server

使用AJAX将数据发送到服务器(GET或POST)并将这些值存储在服务器上的会话变量或cookie中

#3


1  

You can use your local/session storage data and populate some hidden inputs, then submit the respective form in an ajax request. To make things cleaner you can use one hidden input and set it's value into a JSON object created from your storage data.

您可以使用本地/会话存储数据并填充一些隐藏的输入,然后在ajax请求中提交相应的表单。为了使事情更清洁,您可以使用一个隐藏的输入并将其值设置为从存储数据创建的JSON对象。

#4


-3  

No, javascript runs on the client, php runs on the server.

不,javascript在客户端上运行,php在服务器上运行。

#1


4  

'You must remember that Server-Side (PHP) code is read before it converts the code to browser-side code. JavaScript is manipulated browser-side...

'你必须记住,在将代码转换为浏览器端代码之前,会读取服务器端(PHP)代码。 JavaScript被操纵浏览器端...

So one-dimensionally, you cannot pass JavaScript to PHP.

所以一维地说,你不能将JavaScript传递给PHP。

However...

然而...

With Ajax and in your case I suggest JSON you can send JavaScript data to a PHP page and bring the response back to your JavaScript methods. I think this will suit your needs. I can provide a simple example if you want.

使用Ajax,在您的情况下,我建议JSON您可以将JavaScript数据发送到PHP页面并将响应带回JavaScript方法。我认为这符合您的需求。如果你愿意,我可以提供一个简单的例子。

//--example below:

// - 以下示例:

JavaScript:

JavaScript的:

//Ajax Method
function processAjax(queryString, processDiv, responseDiv) {

responseDiv.innerHTML = '';
var myAjax;
try {
    // Modern Browsers-->
    myAjax =new XMLHttpRequest();
} catch (e) {
    // antique ie browsers-->
    try {
        myAjax =new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            myAjax =new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            // Something went wrong
            document.getElementById('processDiv').innerHTML="";
            alert("Your browser malfunctioned!  Please try again. Consider installing a modern browser if the problem persists.");
            return false;
        }
    }
}
myAjax.onreadystatechange = function() {
    if (myAjax.readyState == 4) {
        var ajaxResponse = myAjax.responseText;
                responseDiv.innerHTML = ajaxResponse;
        processDiv.innerHTML = "";

                    //NOTE: HERE IS WHERE AJAX IS FINISHED, SO IF YOU WANT TO DO SOMETHING ELSE HERE YOU CAN!
                    //POST PROCESSING----->
                    // IE: alert('I am finished processing now!');
                    // or call another function:
                    // anotherFunction();

            } else {
        processDiv.innerHTML = '<img src="http://www.mysite.com/images/loadingicon.gif" alt="processing....." />';
    }
}
myAjax.open("GET", queryString, true);
myAjax.send(null);

}


function sendStorage() {

   var helloVar = 'Hello, I am passed to PHP #1';
   var worldVar = 'I am the second value passed to PHP!';
   var processId = 'process_div';
   var resultId = 'result_div';
   var queryString = 'http://www.mysite.com/process.php?hello=' + helloVar + '&world=' + worldVar;

   processAjax(queryString, processId, resultId);

}

Now for some HTML:

现在有些HTML:

<div id="content">
       <div id="process_div"> This is where processing will occur </div>
       <div id="result_div"> This is where my response will display </div>
</div>

Now for a process.php (NOTE: FOR SECURITY, I STRONGLY SUGGEST YOU DON'T REVEAL A SERVER-SIDE PROCESSING PAGE IN YOUR JAVASCRIPT)

现在为process.php(注意:为安全起见,我强烈建议您不要在您的JAVASCRIPT中显示服务器端处理页面)

<?php

  //init
  $hello = '';
  $world = '';
  $errors = 0;

  //set
  //Security note: never trust a URL request.. you should clean all $_GET, $_REQUEST, AND $_POST with the PHP htmlspecialchars() method (take a look at php.net for that)
  (isset($_GET['hello'])) ? $hello = $_GET['hello'] : $errors++;
  (isset($_GET['world'])) ? $world = $_GET['world'] : $errors++;

  //process
  if($errors > 0) {
      echo 'Errors Detected! Missing querystring get data!';
  } else {
      echo '<p>Hello received: ' . $hello . '</p>';
      echo '<p>World received: ' . $world . '</p>';
      //now we can process $hello and $world server side!
  }

?>

?>

Important: you should really look into learning some JSON and $_POST requests as they are more secure, faster and you can easily manipulate returned data. I suggest looking at a library like jquery for simplified examples.

重要提示:您应该学习一些JSON和$ _POST请求,因为它们更安全,更快,您可以轻松地操作返回的数据。我建议查看像jquery这样的库来简化示例。

I have not tested this code, but it should work.. Let me know if you have questions or this does not answer your question.

我没有测试过这段代码,但它应该可以工作..如果您有疑问或者这不能回答您的问题,请告诉我。

Glad to help!

乐意效劳!

#2


2  

Use AJAX to send data to the server (GET or POST) and store these values in a session variable or cookie on the server

使用AJAX将数据发送到服务器(GET或POST)并将这些值存储在服务器上的会话变量或cookie中

#3


1  

You can use your local/session storage data and populate some hidden inputs, then submit the respective form in an ajax request. To make things cleaner you can use one hidden input and set it's value into a JSON object created from your storage data.

您可以使用本地/会话存储数据并填充一些隐藏的输入,然后在ajax请求中提交相应的表单。为了使事情更清洁,您可以使用一个隐藏的输入并将其值设置为从存储数据创建的JSON对象。

#4


-3  

No, javascript runs on the client, php runs on the server.

不,javascript在客户端上运行,php在服务器上运行。