我有一个 php 函数,其中正在创建一些 pdf 文件。我有一个按钮,我想在单击按钮时调用该函数,然后重定向到一个网址。最简单的方法是什么?
最佳答案
如果您需要调用 PHP 方法,我会使用 AJAX。像这样的事情:
var btn = document.getElementById("button_id");
btn.onclick = function () {
// Make AJAX request
// On success, do this:
window.location.href = "url to redirect to";
};
“发出 AJAX 请求”的代码可以轻松在 Google 上搜索到,我将在一分钟内提供它:)
更新:
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Firefox, Chrome, Opera 8.0+, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP.6.0");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP.3.0");
} catch (e) {
throw new Error("This browser does not support XMLHttpRequest.");
}
}
}
}
}
return ajaxRequest;
}
AJAX 代码 -
var req = ajaxFunction();
req.onreadystatechange = function (response) {
if (response.status == 200 && response.readyState == 4) {
window.location.href = "url to redirect to";
}
}
req.open("POST", "your PHP file's URL", true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(null); // Or send any `key=value&` pairs as a string
关于php - 调用 php 函数并在按钮单击时重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12976519/