我正在 Rails 中构建一个表单,它将通过 ajax 编辑现有问题。
提交表单并更新问题后, Controller 中的 update 方法会渲染 update.js.erb,这将再次隐藏表单。
我的问题是 update.js.erb 中的 JavaScript 代码根本没有执行。
我知道该文件正在呈现,因为它显示在服务器输出中,并且当我放置
<% raise params %>
进入它,它起作用了。
但是,即使是最简单的
alert('hello');
对同一文件没有影响。
我已经排除了 javascript 和 jquery 配置问题,因为相同的代码在我的 edit.js.erb 文件中完美运行。它只是在 update.js.erb 中不起作用。
我错过了什么?
编辑:
Firebug 显示没有错误。这是 firebug 网络面板中的响应:
alert('hello');
$('#question_body').replaceWith('<h4><p>jhsdfjhdsb k jdfs j fjfhds <strong>jfshaflksd;hf sdldfs l fdsalkhdfskhdfs</strong>;fd lfdksh hfdjaadfhsjladfhsjadfs ;df sjldfsj dfas hafdsj fdas ;ldfas ldfs df dl;hdf fdh ;fdj ;lfads</p></h4>');
默认更新
编辑2:
这是 Controller 操作:
def update
respond_to do |format|
if @question.update_attributes(params[:question])
format.html { redirect_to @question, :flash => { :success => 'Question was successfully updated.' } }
format.json { head :no_content }
format.js {}
else
format.html { render action: "edit" }
format.json { render json: @question.errors, status: :unprocessable_entity }
end
end
end
最佳答案
在您的 $.ajax
调用中,确保将 dataType
选项设置为 "script"
否则响应可能会以其他方式解释因此不会作为 JS 执行。
关于javascript - Rails update.js.erb 不执行 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18936633/