将数组从带有 JSON 的 Jquery 传递给 PHP

Pass Array FROM Jquery with JSON to PHP

本文关键字:Jquery PHP JSON 数组      更新时间:2023-09-26

嘿伙计们,我阅读了其他一些帖子并尝试了很多,但它仍然对我不起作用。当我提醒数组时,我在第一个站点上得到了所有结果,但在将数据发送到 PHP 后,我只得到一个空结果。 有什么想法吗?

$(document).ready(function() {
$('#Btn').click(function() {
    var cats = [];
    $('#cats input:checked').each(function() {
        cats.push(this.value);
    });
    var st = JSON.stringify(cats);
   $.post('foo.php',{data:st},function(data){cats : cats});
   window.location = "foo.php";     
   }); 
});

菲律宾比索

$data = json_decode($_POST['data']);

谢谢你

当我提醒它时,我的数组看起来像这样 房子/公寓,花园/自然,运动/爱好这是用户可能会选择的几个结果(从复选框)。但是当我把它发布到PHP时,我什么也得不到。 当我使用请求标记(chrome 扩展程序)时,它向我显示类似的东西 原始数据猫=%5B%22房子+主题%22%2C%22flat+items%22%5D

我也尝试过这种方式 - 仍然没有结果

$(document).ready(function() {
$('#Btn').click(function() {
    var cats = [];
    $('#cats input:checked').each(function() {
        cats.push(this.value);
        alert(cats);
    $.ajax({
    type: 'POST',
    url: "foo.php",
    data: {cats:  JSON.stringify(cats)},
    success: function(data){
     alert(data);
     }
   });
  }); 
   window.location = "foo.php";
  }); 
}); 

.php:

$json = $_POST['cats'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
echo "<pre>";
print_r($data);

它让我发疯

采用以下脚本: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

并致电:

var myJsonString = JSON.stringify(yourArray);

所以现在你的代码是

$(document).ready(function() {
$('#Btn').click(function() {
    var cats = [];
    $('#cats input:checked').each(function() {
        cats.push(this.value);
    });
   var st = JSON.stringify(cats);
   $.post('foo.php',{data:st},function(data){cats : cats});
 //  window.location = "foo.php";    // comment this by this page redirect to this foo.php
   });
   }); 

如果 uou 想要重定向,请使用以下代码

-------------------------------------------------
     $.post('foo.php',{data:st},function(data){
       window.location = "foo.php"; 
     });
---------------------------------------------------

菲律宾比索

$data = json_decode($_POST['data']);
var ItemGroupMappingData = []
Or 
var ItemGroupMappingData =
{
"id" : 1,
"name" : "harsh jhaveri",
"email" : "test@test.com"
}
 $.ajax({
            url: 'url link',
            type: 'POST',
            dataType: "json",
            data: ItemGroupMappingData,
            success: function (e) {
// When server send response then it will be comes in as object in e. you can find data //with e.field name or table name
            },
            error: function (response) {
                //alert(' error come here ' + response);
                ExceptionHandler(response);
            }
        });

试试这个:-

    $data = json_decode($_POST['data'], TRUE);

我认为您应该将"window.location = "移动到帖子回调,这意味着它应该等到帖子结束,然后重定向页面。

$.post('foo.php', {
  data : st
}, function(data) {
   window.location = "foo.php";
});