markdown 在Rails中使用.js文件和AJAX进行渲染

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 在Rails中使用.js文件和AJAX进行渲染相关的知识,希望对你有一定的参考价值。

### Controller
* In your controller, have all the necessary variables available for use in the views
* You will also need to have a `respond_to` block that will handle which type of files to render

```ruby
def index
  @var = ...
  @var2 = ...
  
  respond_to do |format|
    format.js
    format.html
  end

end
```

* The syntax above **only works** if you 2 files called `index.js` and `index.html.erb`.
* You would need to specify next to the format which files to render (if they have different names)

---

### `.js` File
* A `.js` file is used to render the results of an AJAX request (which is used to load items on your
page without refreshing the page)
* As mentioned above, you will need an `index.js` file which will target an HTML element on the page
(usually an `id`) and _insert_ HTML into the element by rendering a partial, as an example:

```ruby
# index.js
("#some_id").html("<%= j render partial: "file_name", locals: {@var: var} %>")
```

* Ofcourse, you will need to write the javascript to activate this file:

```javascript

$("#some_form_element").change(function() {
    //capture some value 
    
    $.ajax({
      url: '',//this is the url that will be routed to the controller to have the .js file activated
      type: 'POST',
      data: var: value_captured_above
    })
})
```

* **Even though its not appropriate to use**, you can use a `GET` request to pass in values obtained
from jQuery to use in your controller action. You can then obtain this value by checking `params[]`:

```javascript
$("#..").change(function(){
  // code
  var blah = ...
  
  $.ajax({
    url: `/asfaf/asd/?any_name=${blah}`
    type: "GET"
  })
  
})
```

### View
* Finally, your `.js` file will render an HTML partial that contains HTML on how the results from
the controller will be displayed

以上是关于markdown 在Rails中使用.js文件和AJAX进行渲染的主要内容,如果未能解决你的问题,请参考以下文章

markdown 使用CSV文件播种Rails数据库

Vue 中使用 markdown 和加载.md 文件

如何使用 Redcarpet for Rails 在 Markdown 中嵌入 YouTube 视频?

在rails中使用js.erb

Bootstrap 4 和 Rails 6:$(...).modal 不是“.js.erb”文件中的函数(但适用于其他 .js 文件?)[关闭]

HyperDown.js 这个markdown解析器在浏览器中怎么使用