weixin_33681778 2017-02-28 11:28 采纳率: 0%
浏览 35

阿贾克斯行动两次

I need to improve a client's website and I had detect an strange error in their behaivour.

When the web call one ajax action, it is called twice. I have breakpoints in js call and in the PHP action code, and the js run once (it is good) but PHP run twice.

I don't know what else test.

I had checked:

  • No break links (favicons, or css and js resources, etc)
  • At begining of the event which call the actio, I just had event.preventDefault();
  • At the ending of this event, I had added: return false;
  • At the form tag, I have this: onsubmit="event.returnValue = false; return false;"

Edit: I have this issue over all browsers.

Edit II: code The action in the controller:

public function getMapOffers() {
    $temporal = $this->getOffers('all');
    return $temporal;
}

public function getOffers($offerType = 'all',$opciones=false) {

    // loadModels
    $this->loadModel('Offer');

    $this->autoRender = false; // We don't render a view in this example
    //$this->request->onlyAllow('ajax'); // No direct access via browser URL 

    $this->loadModel('Customer');
    $customer = $this->Auth->user();
    $customer['googleaddress'] = $this->Customer->getDetaultGoogleAddress($customer);
    $latitude_customer = isset($customer['latitude']) ? $customer['latitude'] : 0;
    $longitude_customer = isset($customer['longitude']) ? $customer['longitude'] : 0;

    $data = array();
    $options = array();
    //$pagination_limit = 600;
    $page = isset($this->request->data['page']) ? $this->request->data['page'] : NULL;
    $latitude = isset($this->request->data['latitude']) ? $this->request->data['latitude'] : $latitude_customer;
    $longitude = isset($this->request->data['longitude']) ? $this->request->data['longitude'] : $longitude_customer;
    $category = isset($this->request->data['category']) ? $this->request->data['category'] : '';
    $keyword = isset($this->request->data['keyword']) ? $this->request->data['keyword'] : '';
    //jfc
    $nacionales = isset($this->request->data['nacionales']) && $this->request->data['nacionales'] === "true" ? TRUE : FALSE;

    if( $nacionales ){
        $array_filters = array('national' => 1, 'map' => 'true', 'page' => $page, 'keyword' => $keyword, 'category' => $category, 'latitude' => $latitude, 'longitude' => $longitude);
    }
    else{
        $array_filters = array('map' => 'true', 'page' => $page, 'keyword' => $keyword, 'category' => $category, 'latitude' => $latitude, 'longitude' => $longitude);
    }
    //!jfc

    if ($offerType == 'featured') {
        $isFeaturedRequest = true;
    }

    if ($offerType == 'lastminute') {
        $isLastMinuteRequest = true;
    }

    if ($offerType == 'all') {
        $isFeaturedRequest = true;
        $isLastMinuteRequest = true;
        $data['page'] = $page;
        $options['page'] = $page;            
    }

    if(isset($this->request->data['firstsearch']) && intval($this->request->data['firstsearch']) < 2){
        $options['limit'] = 100;
    }

    $result = $this->Offer->getPublishedOffers($array_filters, $options);
    $data['total'] = 10000;
    $data['map'] = true;


    $data['offers'] = $this->prepareOfferContent($result['offers'],$opciones);

    if ($isFeaturedRequest) {
        $data['featured'] = $this->prepareOfferContent($result['featured'],$opciones);
    }
    if ($isLastMinuteRequest) {
        $data['lastminute'] = $this->prepareOfferContent($result['lastminute'],$opciones);
    }

    if (isset($data['offers']) && empty($data['offers'])) {
        $data['offers'] = '';
    }
    if (isset($data['featured']) && empty($data['featured'])) {
        $data['featured'] = '';
    }
    if (isset($data['lastminute']) && empty($data['lastminute'])) {
        $data['lastminute'] = '';
    }
    $temporal2 = json_encode($data);
    /*try{
        file_put_contents('offers.log', print_r($data, true));
    }
    catch (Exception $e){
        //json_encode($e);
    }*/
    return  $temporal2;
}

ctp file:

    <!--Search-->
    <div class="row">
        <form id="offer-search" class="form form-horizontal" method="post" action="#" accept-charset="UTF-8" onsubmit="event.returnValue = false; return false;">   

            <div class="col-md-12">
                <h1>Buscador de ofertas</h1>
                <div class="col-sm-3 offer-search-item">
                    <input type="hidden" value="1" name="data[firstsearch]" id="firstsearch" />
                        <?php echo $this->Form->input('keyword' , array('class'=>'form-control' ,'id' => 'keywordoffersearch', 'placeholder' => 'Nombre de oferta', 'label' => false )); ?>
                </div>  

                <div class="col-sm-4 offer-search-item" id="divDireccion">
                    <div class="input-group">
                        <span class="input-group-addon" id="mapcurrentgeoposition" title="<?php echo __('I want to send my current position') ?>"><i class="icon-screenshot"></i></span>
                        <?php 
                        if( $customer['googleaddress'] === Configure::read("App.DefaultDataGoogleMaps") ||$customer['googleaddress'] === Configure::read("App.DefaultDataGoogleMaps").", Madrid, Madrid, 28013" ){
                            //todo: quitar el OR, está por un error en la página de perfil
                            $customer['googleaddress'] = "";
                        }
                        echo $this->Form->input('googlemapsaddress' , array('class'=>'form-control' ,'id' => 'googlemapsaddress', 'placeholder' => 'Ubicación', 'label' => false , 'default' => $customer['googleaddress'] ));
                        echo $this->Form->input('latitude', array('type' => 'hidden', 'value' => $latitude , 'id' => 'latitude' ) );
                        echo $this->Form->input('longitude', array('type' => 'hidden', 'value' => $longitude, 'id' => 'longitude'  ) );
                        ?>                              



                    </div>
                </div>


                <div class="col-sm-3 offer-search-item">
                    <?php echo $this->Form->input('categories', array('options' => $categories,'empty' => __('Todos los sectores'), 'class'=>'form-control', 'label' => false, 'id' => 'categorymapfilter'));?>     
                </div>






                <div class="col-sm-2 offer-search-item">
                    <button type="submit" id="submitOfferFilter" class="btn btn-default btn-success"><i class="icon-refresh"></i> <?php echo __('Actualizar ofertas') ?></button>                   
                </div>      


                <div class="col-sm-12 offer-search-item">
                    <?php echo $this->Form->input('nacionales', array('onchange' => 'changeNacionales(this);', 'type' => 'checkbox', 'label' => 'Mostrarme sólo las ofertas nacionales.' , 'id' => 'chkNacionales'  ) ); ?>
                </div>
            </div>





        </form>     
    </div>
    <hr class="normal">
    <!--./Search-->

    <!--Map-->
    <div class="row" style="position: relative">




    <div id="loadingMap" class="col-lg-12" style="position: absolute;z-index: 9999; background-color: #f5f6f6; width: 100%">
        <p class="text-center" style="height: 400px; position: relative">
            <?php echo $this->Html->image("loading.gif", array('width' => '32', 'height' => '32', 'style' => 'position: absolute; top: 50%')) ?>
        </p>
    </div>

        <div class="col-md-12">
            <div id="map-canvas" class="map map_canvas"></div> 
            <hr class="hr-normal">
        </div>



    </div>
    <!--./Map-->


    <!-- Last Minute -->
    <div id="lastMinuteList" class="row" style="margin: 0 -30px">       
    </div>
    <hr class="offers-separator" style="margin: 20px -30px;">
    <!-- ./Last Minute -->


    <!--Offers-->
    <div class="row" style="position: relative">

        <div id="loadingOffers" class="col-lg-12" style="position: absolute;z-index: 9999; background-color: #f5f6f6; width: 100%">
            <p class="text-center" >
                <?php echo $this->Html->image("loading.gif", array('width' => '32', 'height' => '32', 'style' => 'position: absolute; top: 50%')) ?>
            </p>
        </div>


        <div id="featuredOffers" class="hide">
            <div class="row">
                <p class="view-all-featured-wrapper align-left featured-title">
                    <span class="lead"><img width="20" src="/img/mobile/ic_destacado.png" /> Ofertas destacadas</span>
                    <button id="view-all-featured" class="btn btn-link bnt-xs  pull-right">
                        <span id="message-link-featured">
                            <i class="icon-chevron-down"></i> Mostrar todas</span>
                    </button>
                </p>
            </div>




            <div clas="row">
                <div id='lista-main'>
                    <div id="mi-lista-contenedor" class="row" style="position: relative">
                        <ul id='mi-lista'>
                        </ul>


                    </div>
                    <div class="controls center">
                        <button class="btn prev"><i class="icon-chevron-left"></i></button>
                        <button class="btn next"><i class="icon-chevron-right"></i></button>
                    </div>
                </div>
            </div>
        </div>

        <div id="offers" style="display: none">


            <!-- Featured -->
<!--            <div id="featuredOffers" class="hide">
                <div class="row">
                    <p class="view-all-featured-wrapper align-left featured-title">
                        <span class="lead"><img width="20" src="/img/mobile/ic_destacado.png" /> Ofertas destacadas</span>
                        <button id="view-all-featured" class="btn btn-link bnt-xs  pull-right">
                            <span id="message-link-featured">
                                <i class="icon-chevron-down"></i> Mostrar todas</span>
                        </button>
                    </p>
                </div>





                <div clas="row">
                    <div id='lista-main'>
                        <div id="mi-lista-contenedor" class="row" style="position: relative">
                            <ul id='mi-lista'>
                            </ul>


                        </div>
                        <div class="controls center">
                            <button class="btn prev"><i class="icon-chevron-left"></i></button>
                            <button class="btn next"><i class="icon-chevron-right"></i></button>
                        </div>
                    </div>
                </div>
            </div>-->

            <hr class="offers-separator">

            <!-- List offers -->
            <div class="list-offers row">
                <div id="filterList"></div>
            </div>
            <!-- ./List offers -->


            <!-- Paginator -->
                        <!-- <div id="paginator-offers" class="text-center"></div>-->
        </div>



    </div>
    <!--./Offers-->


    <?php echo $this->element('customer/mapoffers') ?> 

            <!-- JFC appbanner -->
        <div class="row">
                        <div class="col-sm-12">
                                <div style="text-align:center;">
                                        <a title="<?php echo __("Descarga la APP de Start Discount Club en tu móvil"); ?>" href="/pages/descarga-app-start-club/">
                                                <img style="margin: 15px 25px 0; max-width: 90%;" src="/img/banner_footer.jpg" />
                                        </a>
                                 </div>
                        </div>
        </div>
</div>



<script type="text/javascript">

        var espublic=false;

        function changeNacionales(that){
        var divDireccion = $("#divDireccion");


        if( $(that).is(':checked') ){
            divDireccion.hide('slow');



        }
        else{
            divDireccion.show('slow');

        }
    }


</script>

Ajax call:

  this.getListOffers = function(options){

var that = this;
var config = options ? options : {};
var page = config.page ? config.page : 1;
var data = {
    'page': page,
    'keyword': this.$keywordOfferSearch.val(),
    'category': this.$categoryMapFilter.val(),
    'latitude': this.$latitude.val(),
    'longitude': this.$longitude.val(),
    'nacionales': this.$chkNacionales.prop( "checked" ),
    'firstsearch': this.$firstsearch
};
//console.log("--------DATA-------");
//console.log(data);
//console.log("------END DATA-----");
$.ajax({
  'type': 'post',
  'url': this.urlAPI,
  'data': data,
  'dataType': 'json',

  success: function( locations ) {
      that.$firstsearch += 1;
    that.createListOffers( locations );

    if (offerMapDesktop.mapType === "mobile") {
      that.setListLoaded({'state': true});
    }
  },

  error: function(e) {
    $.jGrowl(messages.error.basic);
  }

});

};
  • 写回答

1条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 Android URL如何转成视频/音频,可行吗?
      • ¥20 SQL数据查询,子查询
      • ¥15 c++字符串分割问题
      • ¥15 关于#sql#的问题:没有用命令关闭cdc,手动把系统表开启的cdc右键删除了
      • ¥15 vue+uniapp
      • ¥15 android freedom
      • ¥15 使用自定义的类型代替内置类型可行吗
      • ¥15 关于STM32的SPI和ENDAT接口编码器通信的问题
      • ¥15 关于#pdfbox#生成的PDF文件正常,转图片中文乱码的问题,如何解决?
      • ¥15 ADS中有关DAC控件的使用问题