开发者

rails 3 jquery ajax call fails with statusText: "parsererror"

开发者 https://www.devze.com 2023-03-20 14:48 出处:网络
That might be a silly question. Sorry if that\'s the case. On a rails 3 application with the latest jquery-rails gem \"1.0.12\" I am trying to replace html from an ajax call

That might be a silly question. Sorry if that's the case.

On a rails 3 application with the latest jquery-rails gem "1.0.12" I am trying to replace html from an ajax call

$.ajax({
    type: "POST",
    cache: false,
    url: url,
    data: data,
    error: function(jqXHR, textStatus, errorThrown){
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
    },
    success: function(msg){
        alert('Load was performed.');
    }
    });

From the controller I answer the ajax call with htm code from a js.erb file the content of the js.erb file is

<img src="<%=@test%>" id="<%=@test_id%>">

The response is received but parseerror error is triggered. The content type in the header 开发者_如何学Pythonof the response is

Content-Type:text/javascript; charset=utf-8

the jqXHR response in the error callback contains this

Object
abort: function ( statusText ) {
always: function () {
complete: function () {
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
isRejected: function () {
isResolved: function () {
overrideMimeType: function ( type ) {
pipe: function ( fnDone, fnFail ) {
promise: function ( obj ) {
readyState: 4
responseText: "<img src="/images/author_tests/copywriter_photo_2.jpg" id="copywriter-test-4e1c3eb5e09c1657fb000003">"
setRequestHeader: function ( name, value ) {
status: 200
statusCode: function ( map ) {
statusText: "parsererror"
success: function () {
then: function ( doneCallbacks, failCallbacks ) {
__proto__: Object

I tried setting the dataType to text but by doing so the server throws an error

ActionView::MissingTemplate (Missing template [.....] with {:locale=>[:"en-US", :"en-US"], :handlers=>[:rhtml, :rxml, :builder, :haml, :erb, :rjs], :formats=>[:text, "*/*"]}

What I am doing wrong?


What you are returning is actually HTML, not JS. The contents of a js.erb file is passed to the javascript engine for evaluation, so it is choking on your HTML (since that is not valid javascript).

Since you just want to return HTML, and you want to replace an element on the page, try the jQuery .load() method, and give your URL an extension of .html. Then move the contents of your .js.erb file into whatever responds to the html format for your controller.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号