我有一个表单,可以通过AJAX提交,也可以使用提交按钮以普通方式提交。。Ajax部分在这里:
parentForm.onsubmit = function(e) { // e represents trigering event
if(srteValidateMode()){ // works only in WYSIWYG mode
var outputString = srteEditArea.innerHTML; // first we prepare the text output data
outputString = outputString
.replace(/<('/?)strong>/gi, '<$1b>') // unify output tags for all browsers -> B I P (instead of strong em div)
.replace(/<('/?)em>/gi, '<$1i>')
.replace(/<('/?)br>/gi, '<p>')
.replace(/<('/?)div/gi, '<$1p');
document.getElementById('simpleRTEoutput').value=outputString; // pass output string to hidden form field
if (srteAjaxSubmit) { // ajax version - filling FormData
e.preventDefault(); // canceling the submit function - we will call it with Ajax
var srteFormData = new FormData(e.target); // getting form data from submitted form
var ajaxRequest = new XMLHttpRequest(); // now going to invoke AJAX
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
srteShowInfo(ajaxRequest.responseText); // return message and display as info window
}
}
ajaxRequest.open("POST", e.target.action); // getting target script from form action
ajaxRequest.send(srteFormData); // send FormData
}
else { // Standard submit
return true; // true = standard submit will proceed (works ok)
}
}
else {return false;} // on false return form will not be submitted
};
它运行良好。现在我想添加重定向功能——点击另一个(非提交)按钮,并点击一些onclick功能来保存(执行预定义的提交)和重定向。我有这样的想法(未测试),但不确定这可能会起作用,尤其是在AJAX部分。
function srteSubmitForm(redirectTo) {
if (srteAjaxSubmit) { // redirect when submitted via Ajax Call
parentForm.submit(); // save form data
window.location.href = redirectTo; // change location - does it wait for previous function ?
}
else {
parentForm.action = parentForm.action + '?redirect=' + redirectTo; // rest handled by target PHP
parentForm.submit();
}
}
HTML中的按钮看起来像:
<input type="button" onclick="srteSubmitForm('"somepage.php?page=A'")" value="Redirect A">
<input type="button" onclick="srteSubmitForm('"somepage.php?page=B'")" value="Redirect B">
<input type="button" onclick="srteSubmitForm('"somepage.php?page=C'")" value="Redirect C">
我不确定,我是否需要等待AJAX以某种方式完成重定向?或者任何其他方式如何在提交后重定向?
请不要使用jQuery解决方案。谢谢,Jan
为什么不在您的提交方法中添加一个"callback"参数,该参数在调用完成时被调用。
parentForm.submit(function(status){
//The call completed, you can display a confirm message 'Form submitted,
//now redirecting' (because it's not nice to redirect without warning ;)
window.location.href = redirectTo;
});
在您提交的文件中:
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
srteShowInfo(ajaxRequest.responseText);
if(callback instanceof Function) callback(ajaxRequest.responseText);
}
}