我试图在我的Rails应用程序中在Javascript中执行ajax调用,但我得到了一个"ReferenceError:$未定义“错误。但是我的jquery也安装在我的应用程序中。我看过其他主题,但没有解决方案,这就是我为什么要创建这个主题。
我已经在我的environment.js上尝试了下面的代码:
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.append('Provide', new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: ['popper.js', 'default']
}))
module.exports = environment我试着移除涡轮机,没有改变任何东西
这里是我的布局Javascript行:
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>我的application.js文件:
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
//= require jquery3
//= require popper
import "bootstrap"我的javascript ajax调用:
<% content_for :javascript do %>
<script>
var textarea = document.getElementById('biography-editor');
var text = document.getElementById('biography');
var btn = document.getElementById('submit-biography');
function edit_biography() {
btn.innerHTML = 'Sauvegarder';
btn.setAttribute( "onClick", "save_biography()" );
textarea.style.display = 'block';
text.style.display = 'none';
}
function save_biography() {
btn.innerHTML = 'Modifier ma biographie';
btn.setAttribute( "onClick", "edit_biography()" );
textarea.style.display = 'none';
text.style.display = 'block';
var content = textarea.innerHTML;
$.ajax({
url : '/user/updateBiography',
type : 'POST',
data : content
});
}
</script>
<% end %>我希望我的javascript工作并理解这个问题。
谢谢
发布于 2019-11-08 16:48:27
我终于在这里找到了一个解决方案:https://www.botreetechnologies.com/blog/introducing-jquery-in-rails-6-using-webpacker
问题是Rails 6中包含了WebPacker,如果您有相同的问题的话。试着跟着向导走。
谢谢
发布于 2019-11-07 23:23:19
你可以用香草JS
xhr = new XMLHttpRequest();
xhr.open('POST', '/user/updateBiography');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(encodeURI('data=' + content));https://stackoverflow.com/questions/58757426
复制相似问题