weixin_33724046 2015-01-21 06:07 采纳率: 0%
浏览 47

json数组数据格式

So I am trying to pass what I think is a json array through an ajax post, but I am having no luck. If I change the dataType to "text" and just add some text as my data, it works fine, which tells me its my data format.

I am getting a 'null' when dumping data on my php page.

This is what my data looks like before it is posted:

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

Here is the code that generates that data:

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

I suppose that it makes sense that that data doesn't post, as it does not look like any json object I've ever posted, but nonetheless, I sort of expected json_stringify() to be a sort-of catch-all solution.

So my question is, what should I change to properly format this for json?

Sincere thanks for any help. It is greatly appreciated.

  • 写回答

1条回答 默认 最新

  • weixin_33743703 2015-01-21 06:43
    关注

    try passing your data adding key for it, change:

    ...
    data: groups,
    

    to

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

    and on PHP:

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

报告相同问题?

悬赏问题

  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM