【问题标题】:JSON is reordering returned listJSON 正在重新排序返回的列表
【发布时间】:2014-01-27 16:37:56
【问题描述】:

我有一些 jQuery,它将根据另一个选择框的值(它使用 AJAX)来更改选择框的内容。 PHP 以我想要的方式返回数组(按 TypeDescriptionData.name 排序),但列表在 JS 中的某个地方重新排序。有什么想法吗?

PHP 调用:

public function get_descriptions_by_type($typeId) {
    $this->autoRender = false;

    $this->loadModel('TypeDescriptionData');

    $data = array();

    $this->TypeDescriptionData->contain();
    $descriptions = $this->TypeDescriptionData->find('list', array('conditions' => array('type_data_id' => $typeId), 'order' => 'name ASC'));

    if(isset($descriptions) && is_array($descriptions)) {
        foreach($descriptions as $x => $y) {
            $data[$x] = $y;
        }
    }

    echo json_encode($data);
}

这是在上面的 json_encode php 调用之后的 JSON:

{
   "1":"FD 50",
   "9":"Hypercom T4210",
   "2":"Hypercom T7P",
   "8":"Hypercom T7Plus",
   "10":"Nurit 2085",
   "11":"Nurit 8400",
   "12":"Nurit 8400 Lite",
   "17":"Other Terminal",
   "13":"Verifone Tranz 330",
   "14":"Verifone Tranz 380",
   "15":"Verifone Vx510",
   "16":"Verifone Vx510 LE"
}

这是 JS:

$('#TypeType').change(function() {
    $('#TypeDescription').find('option').remove().end();
    $.ajax({
        url:'/TypeData/get_descriptions_by_type/' + $(this).val(),
        type:'POST',
        dataType: 'json',
        success: function( json ) {
            console.log(JSON.stringify(json));
            $.each(json, function(i, value) {
                $('#TypeDescription').prepend($('<option>').text(value).attr('value', i));
            });
        }
    });
});

如果我添加“console.log(JSON.stringify(json));”,这就是 JSON紧接在上面 JS 中的“success:function(json){”之后:

{
   "1":"FD 50",
   "2":"Hypercom T7P",
   "8":"Hypercom T7Plus",
   "9":"Hypercom T4210",
   "10":"Nurit 2085",
   "11":"Nurit 8400",
   "12":"Nurit 8400 Lite",
   "13":"Verifone Tranz 330",
   "14":"Verifone Tranz 380",
   "15":"Verifone Vx510",
   "16":"Verifone Vx510 LE",
   "17":"Other Terminal"
}

【问题讨论】:

  • 原始 JSON 是什么样的? IE。响应的内容。

标签: json


【解决方案1】:

一个json对象是一个关联数组,所以这两个对象实际上是等价的。基本上计算机不记得顺序,只记得键/值对。如果顺序对您来说真的很重要,那么您需要使用其他类型的结构。例如你可以嵌入一个数组:

{
    "beaches" : [
        {"key" : "1", "value" : "FD 50"},
        {"key" : "2", "value" : "Hypercom T7P"},
        {"key" : "8", "value" : "Hypercom T7Plus"}
    ]
}

【讨论】:

    猜你喜欢
    • 2016-06-13
    • 2015-10-31
    • 2015-09-16
    • 2016-09-05
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多