简体   繁体   中英

How to pass HTTP method to window.open

Is there any way to specify the HTTP method (POST, DELETE, PUT) in a window.open call?

I know I can make an Ajax call instead and that allows for specifying the HTTP method, but in this case I want the browser to make the call 'for real' (an follow all redirects, load response proper etc).

I ended up using a hidden form to wrap the HTTP request. The method is specific for my back end (Rails) as it uses the hidden _method input to post a pseudo-PUT or pseudo-DELETE action. With Rails I also had to add the hidden CSFR field . My original HTML is as follows:

<button class="btn action-button btn-danger"
  id="delete-object"
  data-action-href="<%= object_path(@object) %>"
  data-action-method="delete"><i class="icon-trash icon-white"></i>Delete</button>

and the CoffeeScript that makes it happen is:

$("button.action-button").each (index, element) ->               
  $(element).click (eventObject) ->                              
    url = $(this).data("action-href")                            
    httpMethod = $(this).data("action-method")                   
    if httpMethod?                                               
      form = $("<form/>",                                        
        id: "action-method-temp-form"                            
        action: url                                              
        method: "post"                                           
        style: "display: none")                                  
      form.appendTo $(this)                                      
      csfr = $('meta[name="csrf-token"]').attr("content")        
      $("<input/>",                                              
        type: "hidden"                                           
        name: "authenticity_token"                               
        value: "#{csfr}").appendTo form                          
      $("<input/>",                                              
        type: "hidden"                                           
        name: "_method"                                          
        value: httpMethod).appendTo form if httpMethod != "post" 
      form.submit()                                              
    else                                                         
      window.location = url        

I understand this is not exactly what I asked, but it does the same thing. An Ajax call followed by document content replace, by contrast, would not properly handle, among other things, redirects and non-html content-type responses.

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