2011-10-10 2 views
1

Я реализовал телега/JQuery Ajax учебник от этого codeigniter cart and jquery from nettuts+Ajax звонки не работают только в IE

Он работает замечательно во всех браузерах, кроме IE..I'm думать, что это связано с селектором CSS, что возможно, более ранние версии IE не поддерживают. То, что он не делает, это ajaxify добавление в корзину, как это предполагается. Я знаю, что сообщение успешно, но .get и загрузка возвращаемых данных в div не являются. Я знаю, что почта работает, потому что если вы нажмете кнопку корзины обновлений, она покажет все добавленные элементы, которые ajax должен добавить и обновить список без перезагрузки страницы.

Вот мой JS

$(document).ready(function() { 
    /*place jQuery actions here*/ 
    var link = ""; 


    $("ul.products form").submit(function() { 
     // Get the product ID and the quantity 
     var id = $(this).find('input[name=product_id]').val(); 
     var qty = $(this).find('input[name=quantity]').val(); 

     $.post(link + "cart/add_cart_item", { product_id: id, quantity: qty, ajax: '1' }, 
      function(data){ 

      if(data == 'true'){ 

       $.get(link + "cart/show_cart", function(cart){ 
        $("#cart_content").html(cart); 
       }); 

      }else{ 
       alert("Product does not exist"); 
      } 

     }); 

     return false; 
    }); 

    $(".empty").live("click", function(){ 
     $.get(link + "cart/empty_cart", function(){ 
      $.get(link + "cart/show_cart", function(cart){ 
       $("#cart_content").html(cart); 
      }); 
     }); 

     return false; 
    }); 




}); 

Вот обработка PHP для AJAX вызовов ::

<?php 

class Cart extends MX_Controller { // Our Cart class extends the hmvc (MX)Controller class 

function __construct() 
    { 
     parent::__construct(); // We define the the Controller class is the parent. 
     $this->load->model('cart_model'); // Load our cart model for our entire class 
    } 

    function index() 
    { 
     $data['products'] = $this->cart_model->retrieve_products(); // Retrieve an array with all products 

     $data['content'] = 'cart/cart/products'; // Select view to display 
     $this->load->view('index', $data); // Display the page 
    } 

    function add_cart_item(){ 

     if($this->cart_model->validate_add_cart_item() == TRUE){ 

      // Check if user has javascript enabled 
      if($this->input->post('ajax') != '1'){ 
       redirect('cart'); // If javascript is not enabled, reload the page with new data 
      }else{ 
       echo 'true'; // If javascript is enabled, return true, so the cart gets updated 
      } 
     } 

    } 

    function update_cart(){ 
     $this->cart_model->validate_update_cart(); 
     redirect('cart'); 
    } 

    function show_cart(){ 
     $this->load->view('cart/cart/cart.php'); 
    } 

    function empty_cart(){ 
     $this->cart->destroy(); 
     redirect('cart'); 
    } 
    function checkout(){ 
    $numitems=$this->cart->total_items(); 

    if($numitems>1){ 
    //more then 1 item 
    $this->load->library('Paypal_Lib'); 
    $multiproductarray=$this->cart->contents(); 
    //echo var_dump($multiproductarray); return; 
    $this->paypal_lib->add_field('business', $this->config->item('paypal_email')); 
      $this->paypal_lib->add_field('return', site_url('paypal/success')); 
      $this->paypal_lib->add_field('cancel_return', site_url('paypal/cancel')); 
      $this->paypal_lib->add_field('notify_url', site_url('paypal/ipn')); // <-- IPN url 
      $this->paypal_lib->multi_items('true'); 
      $i=1; // keeps track for _number 
      foreach($this->cart->contents() as $items){ 
      $this->paypal_lib->add_field('item_name_'.$i, $items['name']); 
     $this->paypal_lib->add_field('item_number_'.$i, $items['id']); 
      $this->paypal_lib->add_field('amount_'.$i, $items['price']); 
      $this->paypal_lib->add_field('quantity_'.$i, $items['qty']); 
     // $this->paypal_lib->add_field('quantity_'.$i, '10'); 
      $i++; 
      } 
      redirect($this->paypal_lib->paypal_get_request_link());//this sends to paypal 


    }else{ 
    //1 item 
     $this->load->library('Paypal_Lib'); 
     //$singleproductarray=$this->cart->contents(); 
     //echo var_dump($singleproductarray); return; 
     //echo $singleproductarray['name'].$singleproductarray['id'].$singleproductarray['price']; return; 
      $this->paypal_lib->add_field('business', $this->config->item('paypal_email')); 
      $this->paypal_lib->add_field('return', site_url('paypal/success')); 
      $this->paypal_lib->add_field('cancel_return', site_url('paypal/cancel')); 
      $this->paypal_lib->add_field('notify_url', site_url('paypal/ipn')); // <-- IPN url 
      $this->paypal_lib->multi_items('false'); 
      //$this->paypal_lib->add_field('item_name', $singleproductarray['name']); 
     // /$this->paypal_lib->add_field('item_number', $singleproductarray['id']); 
      //$this->paypal_lib->add_field('amount', $singleproductarray['price']); 
       foreach($this->cart->contents() as $items){ 
        $this->paypal_lib->add_field('item_name', $items['name']); 
     $this->paypal_lib->add_field('item_number', $items['id']); 
      $this->paypal_lib->add_field('amount', $items['price']); 
        $this->paypal_lib->add_field('quantity', $items['qty']); 

      } 
      redirect($this->paypal_lib->paypal_get_request_link());//this sends to paypal 

    } 

    } 
} 

/* End of file cart.php */ 
/* Location: ./application/controllers/cart.php */ 




<?php 

class Cart_model extends CI_Model { 

    // Function to retrieve an array with all product information 
    function retrieve_products(){ 
     $query = $this->db->get('products'); 
     return $query->result_array(); 
    } 

    // Updated the shopping cart 
    function validate_update_cart(){ 

     // Get the total number of items in cart 
     $total = $this->cart->total_items(); 

     // Retrieve the posted information 
     $item = $this->input->post('rowid'); 
     $qty = $this->input->post('qty'); 

     // Cycle true all items and update them 
     for($i=0;$i < $total;$i++) 
     { 
      // Create an array with the products rowid's and quantities. 
      $data = array(
       'rowid' => $item[$i], 
       'qty' => $qty[$i] 
      ); 

      // Update the cart with the new information 
      $this->cart->update($data); 
     } 

    } 

    // Add an item to the cart 
    function validate_add_cart_item(){ 

     $id = $this->input->post('product_id'); // Assign posted product_id to $id 
     $cty = $this->input->post('quantity'); // Assign posted quantity to $cty 

     $this->db->where('id', $id); // Select where id matches the posted id 
     $query = $this->db->get('products', 1); // Select the products where a match is found and limit the query by 1 

     // Check if a row has been found 
     if($query->num_rows > 0){ 

      foreach ($query->result() as $row) 
      { 
       $data = array(
        'id'  => $id, 
        'qty'  => $cty, 
        'price' => $row->price, 
        'name' => $row->name 
       ); 

       $this->cart->insert($data); 

       return TRUE; 
      } 

     // Nothing found! Return FALSE! 
     }else{ 
      return FALSE; 
     } 
    } 

    // Needed? 
    //function cart_content(){ 
    // return $this->cart->total(); 
    //} 

} 


/* End of file cart_model.php */ 
/* Location: ./application/models/cart_model.php */ 

Что происходит, после того, как первый элемент загружается в корзину (через AJAX, и успешно), он будет продолжать добавлять элементы, но ajax не будет обновлять элементы списка ul на экране, если я не вручную нажимаю кнопку «Обновить корзину». Проблема существует только в IE

спасибо!

+1

плохо принимаю ответы, когда я их получаю –

+1

Вы получите ответы, когда будете показывать основные усилия по отладке. Требуется 10 секунд, чтобы зафиксировать пару «alert()», чтобы выяснить, вызван ли ваш код. И еще одна минута, чтобы увидеть, работает ли ваш код вне комплексной области ajax. Вы ничего не сделали, но вы ожидаете ответов. –

+0

не рядом с ПК .. может быть не для этого вопроса, но обычно я отправляю весь код. не видят, как оповещения помогут или куда их поместить, поскольку это работает во всех других браузерах. не уверен, что не подходит для того, чтобы ... обновить до конца здесь –

ответ

1

что вы эхо от сервера

это echo true ;, то вы должны использовать if(data == true)

это echo 'true' ;, то вы должны использовать if(data == 'true')

echo 1; то вы должны использовать if($.trim(data) == 1)

попытаться использование $.trim(data) вместо data

надеюсь, что это может быть полезно.

Смежные вопросы