【问题标题】:Passing value to php from local storage using Ajax使用 Ajax 从本地存储向 php 传递值
【发布时间】:2020-07-30 09:26:18
【问题描述】:

我想将值从 js 传递到存储在本地存储中的 php

js

let cartItems = localStorage.getItem("productsInCart");
var jsonString = JSON.stringify(cartItems);

 $.ajax({
    url:"read.php",
    method: "post",
    data: {data : jsonString},
    success: function(res){
    console.log(res);
      }
   }) 

php

<?php
print_r($_POST)
?>

在 .php 上,我得到的只是“array ()”

【问题讨论】:

  • localStorage 总是返回一个字符串,你不需要JSON.stringify
  • 但我仍然只得到空白数组()
  • 你确定你在localStorage中有东西吗?你在 ajax 之前检查过 console.log(cartItems) 吗?它显示了什么?
  • 是的,console.log(cartitems) 完美运行
  • 我刚刚创建了一个简单的example,它可以工作,但不确定你的有什么不同(F9 启动它)。我唯一能想到的是你的localStorage 是空的

标签: javascript php html ajax cart


【解决方案1】:

将@reyno 的方法与名为“store_user_order.php”的同一文件中的所有代码一起使用

  <?php
     if(isset($_POST["data"])) {
     print_r($_POST["data"]);
     }else{
   ?>
    <button>SEND</button><br/>

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js">                 </script>
   <script>
     const cartItems =  localStorage.getItem("productsInCart");
     const jsonString = JSON.stringify(cartItems);

    $("button").click(function() {
     jQuery.ajax({
           url: 'store_user_order.php',
           method: 'post',
           data: {
            data: jsonString
             },
             success: function(res) {
             jQuery('body').append(res);
              },
              error: function(err) {
              jQuery('body').append(err);
          }
       });
      })
 </script>
 <?php } ?>

如果您在本地存储中有项目,这应该可以工作

【讨论】:

    【解决方案2】:

    在测试时,检查值使用method: "get",确保您的测试值不是很大 - 您会在地址栏中看到提交的值。

    为了测试(php + MySQL)我总是使用这种方法:

       success ? changes() : errors_list();`  
    

    我不会用js,请自己处理语法。

    在 .php 上我得到的只是“array ()”

    您收到了一个空的 $ _POST 数组 - 没有发送任何内容。
    因为没有什么要发送,或者发送有错误

    【讨论】:

    • AFAICT 这不能回答问题的任何部分?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 2021-06-29
    • 2014-05-01
    • 2014-10-21
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    相关资源
    最近更新 更多