我有一个php函数,其中正在创建一些pdf。我有一个按钮,我想在按钮单击时调用该功能,然后重定向到URL。最简单的方法是什么?
答案 0 :(得分: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
答案 1 :(得分: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;
}
答案 2 :(得分:0)
<form name="input" action="whatever.php" method="get">
...
<input type="submit" value="Submit">
</form>