I have an image with an onclick. When the click event fires, I want to send an HTTP POST and have the window.location redirect to the response to the POST. How can I do that?
相关问题
- Angular RxJS mergeMap types
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
You could use this function i made:
http://jsfiddle.net/cgarciagl/KU4B6/
Assuming you require to send the POST request asynchronously, you may want to check the example below to get you going in the right direction:
Then you require a JavaScript function that submits an asynchronous HTTP POST request and redirects the browser to a URL received from the HTTP response. You should be able to use
XMLHttpRequest
for such an asynchronous call, as in the following example:Note that for a truly cross-browser
XMLHttpRequest
call, you may want to use a standard-compliant cross-browser XMLHttpRequest implementation like XMLHttpRequest.js, unless you are using some JavaScript framework like jQuery, Prototype, YUI, ExtJS, et al.In addition, also note that the above will only work if you are posting to a script hosted within the same domain, otherwise you will be violating the same-origin policy and modern web browsers will refuse to send the request.
Using jQuery post the data and redirect to your desired location like so:
You could remove the
data: 'formValue=someValue',
if there is no data to pass to the page you want to post to.Just bind the button to the submit method of a form element, and the redirect will happen naturally.
Use a input type image.
When clicking on the image you will be redirected to "someUrl.html" and a post will be sent to it
Instead of
window.location = http.responseText
use the following:document.open()
clears the current content of the page anddocument.write()
inserts the response html code into your page.