简体   繁体   English

将带有ajax的JS数组发送到php

[英]Send the JS array with ajax to php

I have an array made by function .push .我有一个由函数 .push 制作的数组。 How to send this JS array from this to another php file.Below I have attached the code.如何将这个 JS 数组从这个发送到另一个 php 文件。下面我附上了代码。 The two files are game.js and gallery.php.这两个文件是game.js 和gallery.php。

Game.js:游戏.js:

   imgarray.push({"img_name":img_name,"x":x_value,"y":y_value,"w":w_value,"h":h_value});

        var st = JSON.stringify(imgarray);
        $.ajax({
          type: "POST",
          url: "gallery.php",
          data: { data :st},

          success: function(data){
            console.log(st);
            alert("OK");

          }

      });

Gallery.php:画廊.php:

  <?php
  $data = json_decode(stripslashes($_POST['data']))[0];
  foreach($data as $d){
  echo($d. '</br>');
  }?>

I tried the above code, but I dont know why it produces error.我尝试了上面的代码,但我不知道为什么会产生错误。 The error I received is Undefined index: data, from the second file (gallery.php).我收到的错误是 Undefined index: data,来自第二个文件 (gallery.php)。

Can someone help me fix this issue and help me to send the array with ajax to php.有人可以帮我解决这个问题并帮我将带有 ajax 的数组发送到 php.ini 吗?

If in your game.js you are calling .push on an array with a certain object, then the $_POST['data] would give you that array.如果在您的game.js您在具有某个对象的数组上调用.push ,则$_POST['data]将为您提供该数组。 You need to go further inside that array to get to the "push"ed object.您需要在该数组中更进一步才能到达“推送”对象。 Here is how I changed you game.js这是我如何改变你game.js

var imgarray = [];
imgarray.push({
    img_name: "myImg",
    x: "x",
    y: "y",
    w: "w",
    h: "h",
});

var st = JSON.stringify(imgarray);
$.ajax({
    type: "POST",
    url: "gallery.php",
    data: { data: st },

    success: function (data) {
    console.log(st);
    alert("OK");
    },
});
}

and then your gallery.php would change to然后你的gallery.php会变成

$data = json_decode(stripslashes($_POST['data']))[0];
foreach ($data as $d) {
    echo($d. '</br>');
}

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

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