weixin_33734785 2017-07-28 02:33 采纳率: 0%
浏览 42

Ajax DATA更改排序

Im doing a AJAX call with my Wordpress site. It works all perfect except for the ORDER (sort) of the data that is coming out the SUCCESS function.

If I print_r ($service) I validate the correct custom order that I want

But after is send using:

(PHP FILE)

public function closest_services() {

    global $wpdb;

    $servicios_repetidos = $_POST['servicios_repetidos'];

    $lat        = $_POST['latitud'];
    $lng        = $_POST['longitud'];
    $categoria  = array();
    $unit       = $_POST['unit'];
    $distancia  = $_POST['radius'];

    if ( $unit == 'km' ) { $earth_radius = 6371.009 / 1.609344 ; }
    elseif ( $unit == 'mi' ) { $earth_radius = 3958.761; }

    $sql = $wpdb->prepare( "
        SELECT DISTINCT
            p.ID AS service_ID,
            p.post_title AS service_title,
            map_lat.meta_value AS locLat,
            map_lng.meta_value AS locLong,


            %f * 2 * ASIN(SQRT( POWER(SIN(( %f - map_lat.meta_value ) * pi()/180 / 2), 2) 
            + COS( %f * pi()/180) * COS( map_lng.meta_value * pi()/180) 
            * POWER(SIN(( %f - map_lng.meta_value) * pi()/180 / 2), 2) )) 
            AS distance

        FROM $wpdb->posts p
        INNER JOIN $wpdb->postmeta map_lat ON p.ID = map_lat.post_id
        INNER JOIN $wpdb->postmeta map_lng ON p.ID = map_lng.post_id
        WHERE 1 = 1
        AND p.post_type = 'servicios'
        AND p.post_status = 'publish'
        AND map_lat.meta_key = 'et_meta_latitud'
        AND map_lng.meta_key = 'et_meta_longitud'
        HAVING distance <= %d
        ORDER BY distance DESC",
        $earth_radius,
        $lat,
        $lat,
        $lng,
        $distancia      
    );

    $closest_services_query = $wpdb->get_results( $sql );
    $servicio = array();

    foreach ( $closest_services_query as $single_service ):

        $servicio[$single_service->service_ID]["service_ID"]            = $single_service->service_ID;
        $servicio[$single_service->service_ID]["meta_fields"]           = get_post_custom( $single_service->service_ID );
        $servicio[$single_service->service_ID]["service_author"]        = get_post_field ( 'post_author' , $single_service->service_ID );
        $servicio[$single_service->service_ID]["service_author_avatar"] = get_avatar( $single_service->service_ID , '64');
        $servicio[$single_service->service_ID]["service_author_url"]    = bp_core_get_user_domain( $single_service->service_ID );           
        $servicio[$single_service->service_ID]["category"]              = get_the_terms( $single_service->service_ID , 'servicios-categoria');
        $servicio[$single_service->service_ID]["service_title"]         = $single_service->service_title;

        $servicio[$single_service->service_ID]["thumb_url"]             = wp_get_attachment_image_src( get_post_thumbnail_id( $single_service->service_ID ) , 'medium' );

        $servicio[$single_service->service_ID]["distancia"]             = $single_service->distance;

        $servicio[$single_service->service_ID]["precio_servicio_visibilidad"] = get_post_meta( $single_service->service_ID , 'et_meta_precio_visibilidad' , true);

        if ( function_exists( 'get_favorites_button' ) ) 
            $servicio[$single_service->service_ID]["favorite_button"] = get_favorites_button( $single_service->service_ID );

    endforeach;

    //print_r($servicio);
    wp_send_json($servicio);

}

(JQUERY FILE)

function ajax_mapa () {                 
    var center = map.getCenter();

    latitud     = center.lat();
    longitud    = center.lng();

    jQuery( "body" ).after( "<div class='loading'>Loading&#8230;</div>" );

    jQuery.ajax({
        url: ajax_object.ajax_url,
        type: "POST",
        dataType: "JSON",

        data: { 
            'action'    : 'closest_services',
            'latitud'   : latitud,
            'longitud'  : longitud,
            'categoria' : categoria,
            'servicios_repetidos' : servicios_repetidos,
            'unit'      : 'km',
            'radius'    : 15
        },      

        success: function( data, textStatus, jqXHR ) { // Si todo salio bien se ejecuta esto

            console.log(data);
            console.log(textStatus);
            console.log(jqXHR);

            var servicios = [];
            var precio;
            var moneda;
            var url_imangen;
            var html_marker;



            jQuery.each( data, function( id_servicio, info_servicio ) { ... ...});
     } ... ...
     ...
 }) ...
   } ...

The LOG from DATA shows the object ordered by the KEY VALUE instead the custom order that was send before.

If I check the LOG from jqXHR.responseText it have the RIGHT order that I want, so basically the data is being received fine, but something is changing the order.

So, the question is, does anybody knows why is DATA being sorted by KEY VALUE, and how I can fix this?

(LOG of jqXHR WITH CORRECT ORDER - by Distance )

"{"144":

{"service_ID":"144","distancia":"6.043960511486238"},"110":{"service_ID":"110","distancia":"6.040024571156195"},"112":{"service_ID":"112","distancia":"6.040024571156195"},"113":{"service_ID":"113","distancia":"6.040024571156195"},"114":{"service_ID":"114","distancia":"6.040024571156195"},"119":{"service_ID":"119","distancia":"6.040024571156195"},"145":{"service_ID":"145","distancia":"6.040024571156195"},"194":{"service_ID":"194","distancia":"5.025501693483518"},"163":{"service_ID":"163","distancia":"4.985331564912346"},"161":{"service_ID":"161","distancia":"1.3274942401635288"}}"

(LOG of DATA WITH INCORRECT ORDER - by KEY ID )

Object { 110: Object, 112: Object, 113: Object, 114: Object, 119: Object, 144: Object, 145: Object, 161: Object, 163: Object, 194: Object }

Thanks

  • 写回答

1条回答 默认 最新

  • weixin_33701294 2017-07-28 14:44
    关注

    Don't sure if is the best solution, but I manage to make it work by converting the OBJECT to an Array and then sorting the Array.

    Basically I added this code:

    /* ********************** */
    // ordeno por distancia
    /* ********************** */
    var arr = jQuery.map(data, function(value, key){
        return value
    });
    
    function SortByName(a, b){
        var aName = a.distancia;
        var bName = b.distancia; 
    
        return ((aName > bName) ? -1 : ((aName < bName) ? 1 : 0));
    }
    
    arr.sort(SortByName);
    /* ********************** */
    

    Just before de jQuery.each( arr , function( id_servicio, info_servicio ) { ... ...}); function

    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB yalmip 可转移负荷的简单建模出错,如何解决?
  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?