美文网首页
Rails Ajax 笔记

Rails Ajax 笔记

作者: ShinPlus | 来源:发表于2019-02-14 10:58 被阅读0次

ujs使用

安装

Gemfile 中已经使用了 gem 'jquery-rails'
在 application.js 中增加这两行:

//= require jquery
//= require jquery_ujs

案例:
<%= link_to "删除", product, :method => :delete, :data => { :confirm => "点击确定继续" } %>

  1. 使用了 :data => { :confirm => "点击确定继续" }这个属性,为我们添加了 data-confirm="点击确定继续" 这样的 HTML 代码,之后 ujs 将它处理成一个弹出框。
  2. :method => :delete属性,这为我们的连接上增加了 data-method="delete" 属性,这样,ujs 会把这个点击动作,会发送一个 delete 请求删除资源,这是符合 REST 要求的。
  3. <%= f.submit nil, :data => { :"disable-with" => "请稍等..." } %>
    给 a 标签增加 data-disable-with 属性,当点击它的时候,使它禁用,并提示文字信息。这样可以防止用户多次提交表单,或者重复的链接操作。
def create
  sleep 10
  @product = Product.new(product_params)

无刷新页面操作

产生一个 ajax 的请求,我们在表单上增加一个参数 remote: true在表單裡加入remote,這樣ujs就會知道要發非同步請求.
<%= form_for @todo, { remote: true } do |f| %>

这时,ujs 将会调用 jQuery.ajax() 提交表单,此时的请求是一个 text/javascript 请求,Rails 会返回给我们相应的结果,在我们的 action 里,增加这样的声明:在保存(save)成功时,我们返回给视图(view)一个 js 片段

controller

respond_to do |format|
  if @product.save
    format.html {...}
    format.js
  else
    format.html {...}
    format.js
  end
end

新增create.js.erb
创建一个新文件 app/views/products/create.js.erb,在这里,我们将新添加商品,显示在上面的列表中。

$('#productsTable').prepend('<%= j render(@product) %>');
$('#productFormModal').modal('hide');

escape_javascript j render 来的link 处理双引号问题。

app/views/products/_product.html.erb

<tr id="product_<%= product.id %>">
  <td id="product_<%= product.id %>_name"><%= link_to product.name, product %></td>
  <td id="product_<%= product.id %>_price" class="text-right"><%= number_to_currency product.price, unit: "¥" %></td>
  <td>
    <%= link_to t('.edit', :default => t("helpers.links.edit")), edit_product_path(product), :class => 'btn btn-default btn-xs editProductLink', remote: true, data: { type: 'json' } %>
    <%= link_to t('.destroy',
      :default => t("helpers.links.destroy")), product,
      :remote => true,
      :method => :delete,
      :data => { :confirm => t('.confirm', :default => t("helpers.links.confirm", :default => 'Are you sure?')) },
      :class => 'btn btn-xs btn-danger' %>
  </td>
</tr>

json 数据的页面处理

<%= link_to t('.edit', :default => t("helpers.links.edit")), edit_product_path(product), remote: true, data: { type: 'json' }, :class => 'btn btn-primary btn-xs editProductLink' %>

增加remote: true, data: { type: 'json' } 和class .editProductLink

新建一个文件,app/assets/javascripts/products.coffee

jQuery ->
  $(".editProductLink")
    .on "ajax:success", (e, data, status, xhr) ->
      $('#alert-content').hide() [1]
      $('#editProductFormModal').modal('show') [2]
      $('#editProductName').val(data['name']) [3]
      $('#editProductDescription').val(data['description']) [3]
      $('#editProductPrice').val(data['price']) [3]
      $("#editProductForm").attr('action', '/products/'+data['id']) [4]

[3] 填入编辑的信息
[4] 更改表单提交的地址

controller

def edit
  respond_to do |format
    format.html
    format.json { render json: @product, status: :ok, location: @product } [1]
  end
end

[1] 让 edit 方法,返回给我们商品的 json 格式信息。

def update
  respond_to do |format|
    if @product.update(product_params)
      format.html { redirect_to @product, notice: 'Product was successfully updated.' }
      format.json [1]
    else
      format.html { render :edit }
      format.json { render json: @product.errors.full_messages.join(', '), status: :error } [2]
    end
  end
end

[1] 我们让 update 方法,可以接受 json 的请求,
[2] 当 update 失败时,我们需要把失败的原因告诉客户端,它也是 json 格式的。

  $("#editProductForm")
    .on "ajax:success", (e, data, status, xhr) ->
      $('#editProductFormModal').modal('hide')
      $('#product_'+data['id']+'_name').html(  data['name'] )
      $('#product_'+data['id']+'_price').html(  data['price'] )
    .on "ajax:error", (e, xhr, status, error) ->
      $('#alert-content').show()
      $('#alert-content #msg').html( xhr.responseText )

案例

<%= f.collection_select :district, District.all, :id, :title, {prompt: '区'}, { class: 'custom-select', 'data-remote' => true, 'data-type' => 'script', 'data-url' => url_for(controller: 'settings', action: 'fetch_district_detail', format: 'js') } %>
"script": 返回纯文本 JavaScript 代码。不会自动缓存结果。除非设置了 "cache" 参数。注意:在远程请求时(不在同一个域下),所有 POST 请求都将转为 GET 请求。(因为将使用 DOM 的 script标签来加载)
http://www.w3school.com.cn/jquery/ajax_ajax.asp

controller

def show
  @subdistrict = {}
end
def fetch_district_detail
  @subdistrict = Subdistrict.where(district_id: params[:instructor][:district])
end

fetch_district_detail.js.erb

$("#sub-district").html("<%= j select_tag :street, options_from_collection_for_select(@subdistrict, :id, :subtitle), { class: 'custom-select', id: 'sub-district' } %>");

最基本的jquery ajax寫法包含

url:發送非同步請求的對象,也就是索求資料的 server 的網址
method:發送請求的類型,如 GET、POST、DELETE、PATCH 等
data:要附帶在請求裡發送給 server 的資料
dataType:要求 server 回傳的資料格式
success:成功後要執行的 function,function 會帶入 server 回傳的資料

未完成

相关文章

  • Rails Ajax 笔记

    ujs使用 安装 Gemfile 中已经使用了 gem 'jquery-rails'在 application.j...

  • 如何在rails中运用ajax ?

    Rails 应用开发笔记(十) 在本应用里,哪些地方需要用到 Ajax 技术呢? 收藏和点赞功能; 评论功能; ‘...

  • ajax学习笔记

    Ajax学习笔记 Ajax简介 1. Ajax是什么? Ajax : Asynochronous javascri...

  • rails问题总结

    使用ajax异步提交表单在rails中只能使用type=submit的button来提交有data-remote=...

  • Rails笔记

    当表已经建立好,不想生成迁移文件 快速生成与撤销 ??????+ Ruby<% ... %>??????????...

  • rails 笔记

    Rails 入门Ruby on Rails 教程 需要 手动 安装依赖 使用脚手架 生成model rake 命令...

  • 创建rails页面的简单流程

    我司前端大神,想了解rails页面相关的东西,顾有笔记如下。 添加路由rails将一个请求(localhost:4...

  • 如何在rails中运用ajax ?

    在本应用里,哪些地方需要用到 Ajax 技术呢? 收藏和点赞功能; 评论功能; ‘我的主页’中的部分内容的显示(我...

  • 2018-06-01

    # Ajax标签(空格分隔): 笔记整理---[TOC]### 从输入网址开始:- 在学习ajax之前,你应该先了...

  • ajax请求 有时会有状态码0

    资料 【error】jQuery ajax请求错误返回status 0和错误error的问题 【开发笔记】ajax...

网友评论

      本文标题:Rails Ajax 笔记

      本文链接:https://www.haomeiwen.com/subject/lthreqtx.html