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

时间:2013-11-13 08:49:37

标签: javascript php jquery arrays json

嘿伙计们,我读了一些其他帖子并尝试了很多,但它仍然不适合我。 当我提醒数组我在第一个网站上得到所有结果但是在将数据发送到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我什么都没得到。当我使用请求标记(铬扩展)时它向我显示了一些内容:原始数据猫=%5B%22house +主题%22%2C%22平面+项目%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);
它让我发疯了

4 个答案:

答案 0 :(得分:1)

采用此脚本: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
   });
   }); 

//如果您想要转发,请使用以下代码

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

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

答案 1 :(得分:1)

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);
            }
        });

答案 2 :(得分:0)

试试这个: -

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

答案 3 :(得分:0)

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

$.post('foo.php', {
  data : st
}, function(data) {

   window.location = "foo.php";
});