RoR unobtrusive scripting adapter--UJS(一些Javascript的语法糖)

Learn how the new Rails UJS library works and compares with the old version of jquery_ujs that it replaces

rails/actionview/app/assets/javascripts/..

视频:https://gorails.com/episodes/rails-ujs-primer?autoplay=1


介绍
This unobtrusive scripting support file 脚本支持Rails,但不严格绑定在任何backend,也可以用在其他任何应用.

  • force confirmation dialogs for various actions;
  • make non-GET requests from hyperlinks;从超级链接制作非get请求
  • make forms or hyperlinks submit data asynchronously with Ajax;用Ajax制作表格或链接提交异步数据
  • 当已经点击提交按钮时,自动防止多次点击,导致重复提交。

These features are achieved by adding certain data attributes to your HTML markup. 

这些功能是通过增加了data attributes到Http markup来实现的。

⚠️抛弃了jquery,使用coffeescript编译的。新要点:

  1. You won't get jQuery anymore in your Rails 5.1 applications
  2. Rails is starting to push you towards building your forms that all submit with AJAX requests

data = new FormData()


使用

rails app 直接在application.js中加上//= reqquire rails-ujs。

如果使用gem Webpacker或者其他的JS bundler,在主要main JS file增加以下代码:

import Rails from 'rails-ujs'; Rails.start()

定义了一些方便的语法糖,比如:

Rails.disableElement(document.getElementById("form_submit"))

解释:让link, button, form, formSubmit元素不能使用。还有enableElement(),让元素可以使用。

rails/actionview/app/assets/javascripts/rails-ujs/features/disable.coffee文件中定义的。

remote.coffe文件有处理ajax 请求的完美案例格式:⚠️这个格式是coffee格式。

Rails.ajax(

type: method or 'GET'
url: url
data: data
dataType: dataType


# stopping the "ajax:beforeSend" event will cancel the ajax request
beforeSend: (xhr, options) ->
  if fire(element, 'ajax:beforeSend', [xhr, options])
    fire(element, 'ajax:send', [xhr])
  else
    fire(element, 'ajax:stopped')
  return false
success: (args...) -> fire(element, 'ajax:success', args)
error: (args...) -> fire(element, 'ajax:error', args)
complete: (args...) -> fire(element, 'ajax:complete', args)
crossDomain: isCrossDomain(url)
withCredentials: withCredentials? and withCredentials isnt 'false'

 

案例:视频5.40分,我也实操成功了✌️

我写了一个只有一个输入框的表格,在chrome-inspect-console上声明一个form格式:

var data = new FormData()

data.append("post[content]", "输入的value")   

#post[content]是输入框的name, 具体可见webAPI, 用于附加一个新的value到一个已存在的 key

然后使用:

Rails.ajax({url: '/posts', type:"POST", data: data})

就正确添加了数据✌️

Csrf.coffee文件

Rails.csrfToken()
"SGFmdd/odcWc625LdYvcwUgi3jt+ou2H7FnKtH448qEksRvE0SHRESMuWS11wNaIrXicnnibw2VDaSeHIJt/tw=="

用于生成随机token。用于api

form.coffee文件

Rails.serializeElement()方法,一次性得到当前表格中已经输入的所有信息。

> var data1 = Rails.serializeElement(document.getElementsByTagName("form")[0])
undefined
> data1
"utf8=%E2%9C%93&authenticity_token=LSfv%2F12dCBYWSg%2FSgNCGQ5n4oV9h1wNBQD4YxqkgAPxB95JOU1SswqmPOLSAm4wKfKLj%2BmfuLaPvDvX194ON6g%3D%3D&post%5Bcontent%5D=xzczxxcz"
> Rails.ajax({url: '/posts', type:"POST", data: data1})
undefined

数据被存入。

猜你喜欢

转载自www.cnblogs.com/chentianwei/p/9302299.html
今日推荐