使用自定义格式

时间:2015-08-06 10:49:07

标签: javascript jquery ajax json

尝试通过GET发送json数据 Json数据:

var data = {
    country: {
        name: "name",
        code: 1
    },
    department: {},
    cars: ["bmw", "ferrari"],
    books: []
}

发送代码:

var posting = $.ajax({
    url: "/do",
    type: "GET",
    traditional: true,
    data: data,
    dataType: "json"
});

posting.done(function (data) {
    // handle result
});

如果traditional = true,则(解析,解码)查询字符串为

country[name]:name
country[code]:1
cars[]:bmw
cars[]:ferrari

如果traditional = false,则(解析,解码)查询字符串为

country:[object Object]
department:[object Object]
cars:bmw
cars:ferrari

理想的应该是

country:{"name": "name", "code":1}
cars:bmw
cars:ferrari

country:{"name": "name", "code":1}
cars:["bmw", "ferrari"]

换句话说,应省略空对象和数组。应该正确编码对象。尝试使用不同的contentType以及JSON.stringify(),没有运气。有办法吗?

3 个答案:

答案 0 :(得分:1)

根据我的理解,我理解的问题是在url中发送多维json数组。我在本地主机上测试了以下代码。希望这会帮助你。我比你的声誉更年轻,但只是想帮助

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
var data = {
    country: {
        name: "name",
        code: 1
    },
    department: {},
    cars: ["bmw", "ferrari"],
    books: []
}

    data = $.param(data);

    var posting = $.ajax({
        url: "test.php",
        type: "GET",
        traditional: true,
        data: data,
        dataType: "json"
    });

    posting.done(function (data) {
        console.log(data);
    });
    </script>

PHP文件

    <?php
    echo "<pre>"; print_r($_REQUEST); echo "</pre>";
    ?>

结果我得到了

<pre>Array
(
    [country] => Array
        (
            [name] => name
            [code] => 1
        )

    [cars] => Array
        (
            [0] => bmw
            [1] => ferrari
        )

)
</pre>

答案 1 :(得分:1)

JS Fidle Demo

var data = {
    country: {
        name: "name",
        code: 1
    },
    department: {},
    cars: ["bmw", "ferrari"],
    books: []
};

function isEmpty(obj) 
{
    for(var prop in obj) 
    {
        if(obj.hasOwnProperty(prop))
            return false;
    }
    return true;
}

function removeFirstLevelEmptyPropertiesFromJSON(obj)
{
  var isArray = obj instanceof Array;
  for (var k in obj)
  {
      if (obj[k] instanceof Array)  
      {
          if(obj[k].length == 0)
              delete obj[k];
      }
      else
      {
          if(isEmpty(obj[k]))
              delete obj[k];
      }
  }
}
removeFirstLevelEmptyPropertiesFromJSON(data);

var modifiedData = JSON.stringify(data);
alert(modifiedData);

答案 2 :(得分:1)

我通过在一个key = value对中发送整个对象来改变发送json数据的逻辑:

$.each(data, function (key, value) {
    if ($.isEmptyObject(value)) {
        delete data[key];
    }
});

var posting = $.ajax({
    url: "/do",
    type: "GET",
    traditional: false,
    data: "data=" + JSON.stringify(data),
    dataType: "json"
});

并在服务器端进行解析。