简体   繁体   English

如何通过ajax向PHP传递和检索JSON函数作为数据?

[英]How to pass and retrieve JSON function as data via ajax to PHP?

I'm working on shopping cart. 我正在购物车上。 Now I need to pass the array of objects added into shopping cart which is stored in localStorage to php page in order to insert into database. 现在我需要将添加到购物车中的对象数组传递给php页面,该对象存储在localStorage中,以便插入数据库。

console.log(localStorage.getItem("shoppingCart"));

Above logs out, the following: 上面注销,以下内容:

[{"name":"Banana","price":1.33,"count":5},{"name":"Apple","price":1.22,"count":5},{"name":"Shoe","price":22.33,"count":1}]

Now I'm trying to pass this JSON string to a php page called submit_cart.php and retrieve the string in php page correctly, how do I do that? 现在,我正在尝试将此JSON字符串传递到一个名为Submit_cart.php的php页面,并正确地在php页面中检索该字符串,我该怎么做? Currently it's sending and receiving empty data. 目前,它正在发送和接收空数据。

$("#submit-cart").click(function(event){
                console.log("****TEST LOG ***");
                console.log(localStorage.getItem("shoppingCart"));
                var data = localStorage.getItem("shoppingCart");
                $.ajax({
                  type: "POST",
                  dataType: "json",
                  url: "submit_cart.php",
                  data: data,
                  success: function(data) {
                    console.log("******success******");
                    console.log(data);//this logs []
                  }
                 });
            });

In submit_cart.php 在submit_cart.php中

<?php
$return = $_POST;
$return["json"] = json_encode($return);
$data = json_decode($return["json"], true);

echo json_encode($return["json"]);
  ?>

EDITED as suggested answer and it's working now: 编辑为建议的答案,它现在可以工作:

$("#submit-cart").click(function(event){
                console.log("****TEST LOG ***");
                console.log(localStorage.getItem("shoppingCart"));
                var data = localStorage.getItem("shoppingCart");

            $.ajax({
            type: "POST",
            dataType: "json",
            contentType: 'application/json',
            url: "submit_cart.php",
            data: data,
            success: function(data) {
            console.log("******success******");
            console.log(data);//this logs []
            }
            });
            });

In submit_cart.php 在submit_cart.php中

<?php
$_POST = json_decode(file_get_contents('php://input'),true);

print_r($_POST);
  ?>

On the ajax request set the content type to json and on the php side read the json from php://input 在ajax请求上,将内容类型设置为json,在php端,从php:// input读取json

$.ajax({
  type: "POST",
  dataType: "json",
  contentType: 'application/json',
  url: "submit_cart.php",
  data: data,
  success: function(data) {
    console.log("******success******");
    console.log(data);//this logs []
  }
});
$_POST = json_decode(file_get_contents('php://input'),true);
// then use post as usual

Both are wrong if you want to get the values from $_POST . 如果要从$_POST获取值,两者都是错误的。 You need to send key-value pairs to the server and then you can access them in $_POST by these keys. 您需要将键值对发送到服务器,然后可以通过这些键在$_POST访问它们。

To send everything in 1 variable, you could do something like: 要将所有内容发送到1个变量中,您可以执行以下操作:

...
var data = {json: localStorage.getItem("shoppingCart")};
...

Note that sending an object is always a good idea as jQuery will take care of encoding the data correctly when you use an object. 请注意,发送对象始终是一个好主意,因为当您使用对象时,jQuery会正确编码数据。

And then you can get it in php like: 然后,您可以像这样在php中获取它:

// you only need this, no additional encoding / decoding
$data = json_decode($_POST["json"], true);

Your data is already encoded as you mention in your question console.log(localStorage.getItem("shoppingCart")); 正如您在问题console.log(localStorage.getItem("shoppingCart"));提到的那样,您的数据已经被编码console.log(localStorage.getItem("shoppingCart"));

output is 输出是

[{"name":"Banana","price":1.33,"count":5},{"name":"Apple","price":1.22,"count":5},{"name":"Shoe","price":22.33,"count":1}]

So in your ajax request 所以在你的ajax请求中

data: { json_data:data} ,

in this case data work as object and it is easy to fetch value. 在这种情况下,数据作为对象工作,并且很容易获取值。

and in php file 并在php文件中

echo $_POST["json_data"];

您不在此处向目标页面发送任何数据。在ajax内部,使用data:参数发送数据。然后在ajax外部使用.done()函数代替使用success函数,在结果处理方面,done函数更好。您可以使用开发人员工具网络检查数据是否正在传输。显示所有请求和响应数据。希望可以解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM