Upgrade to Pro — share decks privately, control downloads, hide ads and more …

AJAX Implementation.pdf

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
Avatar for Liu Ho Yin Liu Ho Yin
November 11, 2012
60

AJAX Implementation.pdf

Avatar for Liu Ho Yin

Liu Ho Yin

November 11, 2012

Transcript

  1. Basic MVC Concept HTTP Request Routing Controller Method Display HTML

    Insert into layout & show to user 12年10月20日星期六
  2. Trigger JS from View In views/store/index.html.rb <%= button_to t('.add') ,line_items_path(:product_id

    => product), :remote=>true %> send a JS request to a path with POST request (/line_itmes) when we click add to Cart button 12年10月20日星期六
  3. Process JS request @line_item = @cart.add_product(product.id) Return the line_item added

    into cart format.js { @current_item = @line_item} Respond to the JS request, by convention, go to execute js.erb with the same name (in this example: create.js.erb) 12年10月20日星期六
  4. Execute create.js.erb $('#cart').html('<%= escape_javascript(render(@cart))%>'); Inside <%= %>, it is ruby

    code render @cart inside <%= %> which simply return HTML using _cart.html.erb under views/carts/ 12年10月20日星期六
  5. Execute create.js.erb (2) escape_javascript just for correct escape in javascript(“

    ” and ‘ ’ are very important) Most important, $('#cart').html(_cart.html.erb we returned), it is a jQuery syntax which put the HTML we return into the element with id cart, You can write it in traditional javascript syntax, document.getElementById(“cart”).innerHTML = <%= xxx %>; 12年10月20日星期六
  6. Summary 1. Produce a JS request to the line_itmes_path which

    is belong to line_itmes_controller when we click Add to cart button 2. line_items_controller JS processes the we made and execute create.js.erb 3. render @cart is Ruby code which simply generates some HTML using _cart.html.erb 4. Put the HTML generated into the the DOM element with id of cart 5. The HTML in the page will be dynamically changed. 12年10月20日星期六