简体   繁体   中英

How can I get an ajax request to behave like a standard HTTP form submit

This is for the html representation on e restlet server, this is to enable forms to be committed with PUT and DELETE http verbs.

<script type="text/javascript">
            function submitFormXMLHttpRequest(meth, url, formname){

            var xmlhttp;
            var params;
            var form = document.getElementById(formname);
            var fieldcount = form.elements.length;
            if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
              }

            var form = document.getElementById(formname);
            for (i=1; i<=(fieldcount-1); i++) {

                if(form.elements[i].name != "") params = params + form.elements[i].name + "=" + form.elements[i].value + "&";

            }
            //alert(params);
            xmlhttp.open(meth, url+"?"+params, true);
            xmlhttp.send();

            }
    </script>`

`(Inserting HTML code example seems a problem, but here's the form)

form id="r1" action="resource1" method="PUT" !--some ftl markup form input fields etc-- button onclick='submitFormXMLHttpRequest("PUT", "resource1" , "r1");' type="button"Submit/button input type="submit" value="Submit" /`

When the button is pressed the PUT verb shows up in the server logs and is dealt with correctly. But the restlet would then ordinarily respond with the next representation of the results of the submit. This doesn't happen because it goes through as an ajax request. If I add Response.Redirect(url, true) it ends up submitting the form a second time as a GET.

The fact that your restlet handle your request as an Ajax request is probably because of the header set by XMLHttpRequest.

In order to avoid it, you could try to remove this header :

if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
    xmlhttp.setRequestHeader("x-requested-with", null);
}

Because generally, it will be defined with "XMLHttpRequest", indicating it's an ajax request.

Edit: I know that with Play! Framework, you can force the method (PUT & DELETE) through the use of x-http-method-override= that can be very useful because those two actions are not common in a html page. Maybe you can find something similar in restlet?

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