我有一个 php 函数,其中正在创建一些 pdf。我有一个按钮,我想在单击按钮时调用该函数,然后重定向到一个 url。最简单的方法是什么?
问问题
695 次
3 回答
3
如果您需要调用 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 请求”的代码可以很容易地用谷歌搜索,我会在一分钟内提供它:)
更新:
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
于 2012-10-19T14:37:38.177 回答
1
有多种方法可以做到这一点。我会在 ajax 中调用 PHP 函数并根据函数返回值进行重定向。以下示例使用 jQuery:
jQuery:
$.ajax({
url: 'createpdf.php',
success: function(data) {
if (data) window.location = 'link/to/new/path';
}
});
PHP:
function create_pdf(){
//Create PDF
//If PDF was created successfully, return true
return true;
}
于 2012-10-19T14:49:00.680 回答
0
<form name="input" action="whatever.php" method="get">
...
<input type="submit" value="Submit">
</form>
于 2012-10-19T14:40:16.910 回答