简体   繁体   中英

How do I display the text from a Rails AJAX JSON response - Javascript is returning [object HTMLDocument]

I have a Rails app where I created an AJAX / JSON controller to do some dynamic HTML updates in the view. I followed this guide: https://www.rubyguides.com/2019/03/rails-ajax/

I make a call like this: ../related.json?vendor_id=1&budget_id=1 and it returns the raw HTML partial I want to update (just a bunch or table rows).

My call looks like this:

    Rails.ajax({
      url: url,
      type: 'GET',
      success: function(data) { 
        document.getElementById("related").innerHTML = "data"
//        alert(data)
      }
    })

If I manually view the JSON request in the browser the HTML output is as expected. However when I try to replace the HTML or even view the data in a test alert I get back [object HTMLDocument] . The guide I followed used data.html to feed the innerHTML but that doesn't work for me. Not sure if that's a UJS / JQuery issue.

How do I set that DOM element with the raw text from the JSON call?

您可以使用 JSON.stringify 函数将原始文本转换为 html:

document.getElementById("related").innerHTML = JSON.stringify(data)

I did some digging and tried this in my controller:

format.json { render  partial: 'related' } 

vs

format.json { render html: render_to_string( partial: 'related' ) } 

This did the trick - I figured that I was feeding the JSON request the wrong data - looks like once I feed it raw text vs html it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM