我有一个带有onclick的图片。当点击事件触发时,我想发送一个HTTP POST请求并让window.location重定向到POST响应。我该如何实现?
我有一个带有onclick的图片。当点击事件触发时,我想发送一个HTTP POST请求并让window.location重定向到POST响应。我该如何实现?
只需将按钮绑定到表单元素的提交方法上,重定向自然会发生。
<script type='text/javascript'>
function form_send(){
f=document.getElementById('the_form');
if(f){
f.submit();
}
}
</script>
<form method='post' action='your_post_url.html' id='the_form'>
<input type='hidden' value='whatever'>
</form>
<span id='subm' onclick='form_send()'>Submit</span>
假设你需要异步发送POST请求,你可能想要检查下面的示例,以帮助你朝正确的方向前进:
<img src="my_image.png" onClick="postOnClick();">
你需要一个JavaScript函数来提交异步HTTP POST请求并将浏览器重定向到从HTTP响应中接收到的URL。 你可以使用 XMLHttpRequest
来进行这样的异步调用,就像以下示例中一样:
function postOnClick()
{
var http = new XMLHttpRequest();
var params = "arg1=value1&arg2=value2";
http.open("POST", "post_data.php", true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
window.location = http.responseText;
}
}
http.send(params);
}
请注意,要想实现真正跨浏览器的XMLHttpRequest
调用,您可能需要使用符合标准的跨浏览器XMLHttpRequest实现,如XMLHttpRequest.js,除非您正在使用一些JavaScript框架,如jQuery、Prototype、YUI、ExtJS等。
另外,请注意,上述方法仅在您向同一域中托管的脚本发布时才有效,否则将违反同源策略,现代Web浏览器将拒绝发送该请求。
http.responseText
将只包含URL。你的脚本为什么要返回HTML?有特别的原因吗? - Daniel Vassallo在使用时,应该避免使用window.location = http.responseText
,而应该使用以下代码:
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
document.open();
document.write(http.responseText);
}
}
document.open()
清除页面上当前的内容,document.write()
将响应的HTML代码插入到您的页面中。
function redirect_by_post(purl, pparameters, in_new_tab) {
pparameters = (typeof pparameters == 'undefined') ? {} : pparameters;
in_new_tab = (typeof in_new_tab == 'undefined') ? true : in_new_tab;
var form = document.createElement("form");
$(form).attr("id", "reg-form").attr("name", "reg-form").attr("action", purl).attr("method", "post").attr("enctype", "multipart/form-data");
if (in_new_tab) {
$(form).attr("target", "_blank");
}
$.each(pparameters, function(key) {
$(form).append('<input type="text" name="' + key + '" value="' + this + '" />');
});
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
return false;
}
$('#btn').button().click(function() {
redirect_by_post('http://pamppi.info/jotform-testing/thankyou/postvars.php', {
variable1: 'Carlos',
variable2: 'Garcia'
}, true);
});
$.ajax({
type: 'POST',
url: 'receivedata.asp',
data: 'formValue=someValue',
success: function(data){
window.location = data;
}
});
如果没有要传递到要发布的页面的数据,则可以删除data: 'formValue=someValue'
。
<form action="someUrl.html" method="POST">
<input type="image" src="img.png" width="30" height="30" alt="Submit">
</form>
当点击图片时,您将被重定向到“someUrl.html”,并向其发送一篇文章