简体   繁体   中英

How do you fake a .xhr request using fetch() and vanilla JavaScript?

I am working on stripping all of the jQuery out of a website and replacing it with plain JS. First off I have no control over the backend. I can not change anything server side. So the api will run my request through this:

def render_created_comment(comment)
    if request.xhr?
      render :partial => "comments/postedreply", :layout => false,
        :content_type => "text/html", :locals => { :comment => comment }
    else
      redirect_to comment.path
    end
  end

This is setup so the site can process normal js requests and those who refuse to use JS and treat the site like it is 1999.

So I need to write a fetch request that fakes being an .xhr , is that possible? I can already send the form data but I end up with the redirect which I am trying to avoid.

When you use fetch() add the X-Requested-With: XMLHttpRequest header. This is essentially what jQuery and other frameworks do.

fetch(url, {
    headers: {
        'X-Requested-With': 'XMLHttpRequest'
    }
}

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