json数组数据格式化

json array data formatting

所以我试图通过 ajax post 传递我认为是 json 的数组,但我没有运气。如果我将数据类型更改为 "text" 并仅添加一些文本作为我的数据,它工作正常,这告诉我它是我的数据格式。

在我的 php 页面上转储数据时出现 'null'。

这是我的数据在 posted 之前的样子:

[{"name":"La Sal, UT","type":"city"},{"name":"Utah, US","type":"state"},{"name":"United States","type":"country"}]

这是生成该数据的代码:

var groups=[];

    if(town && stateShort){
      groups.push({name: town+", "+stateShort,
               type:"city"
      });
    }

    if(neighborhood && stateLong){
      groups.push({name: neighborhood+", "+stateShort,
               type:"neighborhood"
      });
    }

    if(stateLong && countryShort){
      groups.push({name:stateLong+", "+countryShort,
               type:"state"
      });
    }

    if(countryLong){
      groups.push({name:countryLong,
               type:"country"
      });
    }

     groups = JSON.stringify(groups);
     console.log(groups);

     $(document).ready(function(){

      $.ajax({
            type: "POST",
            url: "check_groups.php",

            data: groups,
            dataType: 'json',
            success: function (data) {
                alert("success");
            },
            error: function(xhr) {
            if(xhr.status == 422) {
              alertValidationErrors(parseErrors(xhr));
            } else {
              alert('An error occurred while processing the request.');
            }
            }   
        });    
     });

我认为该数据不 post 是有道理的,因为它看起来不像我曾经 post 编辑过的任何 json 对象,但尽管如此,我有点希望 json_stringify() 成为一种万能的解决方案。

所以我的问题是,我应该更改什么以便为 json 正确设置格式?

衷心感谢您的帮助。不胜感激。

尝试传递您的数据为其添加密钥,更改:

...
data: groups,

…
data: {"groups" : groups},
…

以及 PHP:

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