17 มกราคม 2555

JQuery + JSON data เรียงลำดับไม่เหมือนกันใน Browser Firefox, IE, Chrome

วันนี้เจอปัญหาใช้ jquery ดึงข้อมูลจาก php array เป็น json แล้วใน IE / firefox / chrome เรียงไม่เหมือนกัน

$.ajax({
                    type: 'POST',
                    url: $('#ProductForm').attr('action'),
                    data: $('#ProductForm').serialize(),
                    dataType: 'json',
                    beforSend: function(){
                        $('#status').addClass('loading');
                    },
                    success: function(data){
                        console.log("%s", "success callback generate HTML option..");
                        
                        if(data != null){
                            //$('#ProductId').html('').show();
                            $.each(data.products, function(key, value){
                                optionTag = '';
                                console.log("appending : %s", optionTag);
                                //$('#ProductId').append(optionTag)
                            });
                        }
                        $('#status').removeClass('loading');
                    },
                    error: function(xhr, status){
                        //$('#ProductId').hide();
                        $('#status').removeClass('loading');
                        console.log("Ajax error status code: %d text: %s", xhr.status, xhr.statusText)
                    }
                });

ในฝั่งเซอฟเวอร์ SQL query ข้อมูลโดยกำหนด ORDER BY `reference` ASC ให้เรียงตามรหัสสินค้า
แล้วใช้ PHP json_encode() response กลับมาเป็น json key/value หน้าตาแบบนี้

ตัวอย่าง response ข้อมูลเรียงลำดับตามชื่อ
{"products":{"1040":"16PHOTO","1037":"16RELAY","1035":"8RELAY","1034":"8SS R\/L out","1024":"AD\/DA","1005":"USB Starter"}}