Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

jquery - Rails update.js.erb not executing javascript

I am building a form in rails that will edit an existing question via ajax.

After the form is submitted and the question has been updated, the update method in the controller renders update.js.erb, which will hide the form again.

My problem is that the javascript code in update.js.erb is not executing at all.

I know that the file is rendering because it shows up in the server output, and when I put a

<% raise params %>

into it, it works.

However, even the simplest

alert('hello');

has no effect in the same file.

I've ruled out javascript and jquery configuration issues because the same code works perfectly in my edit.js.erb file. It's just not working in update.js.erb.

What am I missing?

Edit:

Firebug shows no errors. Here is the response in firebug's network panel:

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>');

def update

Edit 2:

This is the controller action:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your $.ajax call make sure to set the dataType option to "script" otherwise the response could be interpreted in other ways and thus not executed as JS.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...