有没有办法可以通过JS函数运行php函数?
类似的东西:
<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php
query("hello"); ?>";
}
</script>
<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;"
onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
我基本上想运行php函数query("hello")
,当我点击名为“Test”的href时会调用php函数。
答案 0 :(得分:139)
这实质上是AJAX 的。您的页面加载,并向元素添加事件。当用户触发事件时,例如通过点击某些内容,您的Javascript会使用XMLHttpRequest object向服务器发送请求。
服务器响应后(可能是输出),另一个Javascript函数/事件为您提供了一个处理该输出的位置,包括像其他任何HTML一样将其粘贴到页面中。
你可以使用普通的Javascript“手动”完成,或者你可以使用jQuery。根据项目的大小和特定情况,使用普通的Javascript可能会更简单。
在这个非常基本的示例中,我们会在用户点击链接时向myAjax.php
发送请求。服务器将生成一些内容,在本例中为“hello world!”。我们将使用标识output
。
javascript
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
HTML
<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>
PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
尝试一下:http://jsfiddle.net/GRMule/m8CTk/
可以说,这是很多Javascript代码。当然,您可以通过拧紧块或使用更简洁的逻辑运算符来缩短它,但仍然有很多事情要做。如果你计划在你的项目中做很多这类事情,你最好使用javascript库。
使用上面的相同HTML和PHP,这是您的整个脚本(页面上包含jQuery)。我已经收紧了一些代码,以便更加符合jQuery的一般风格,但你明白了这一点:
// handles the click event, sends the query
var function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
尝试一下:http://jsfiddle.net/GRMule/WQXXT/
不要急于使用jQuery:添加任何库仍然会为您的项目添加数百或数千行代码,就像您编写它们一样。在jQuery库文件中,您将找到与第一个示例中类似的代码,再加上更多。这可能是件好事,也可能不是。计划并考虑项目的当前规模和未来扩展的可能性以及目标环境或平台。
如果您只需要这样做,请编写一次简单的javascript,然后就完成了。
<强>文档强>
XMLHttpRequest
- https://developer.mozilla.org/en/XMLHttpRequest XMLHttpRequest
- http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx jQuery.ajax
- http://api.jquery.com/jQuery.ajax/ 答案 1 :(得分:15)
PHP在服务器上进行评估; javascript在客户端/浏览器中进行评估,因此您无法直接从javascript 调用PHP函数。但您可以使用AJAX向服务器发出一个HTTP请求,该服务将激活PHP函数。
答案 2 :(得分:11)
从JS执行PHP的唯一方法是AJAX。 您可以将数据发送到服务器(例如,GET /ajax.php?do=someFunction) 然后在你写的ajax.php中:
function someFunction() {
echo 'Answer';
}
if ($_GET['do'] === "someFunction") {
someFunction();
}
然后,用JS(我使用jQuery来发出AJAX请求)来回答答案
可能你需要一些答案格式。请参阅JSON或XML,但JSON易于使用JavaScript。在PHP中,您可以使用函数json_encode($ array);将数组作为参数。
答案 3 :(得分:2)
我最近发布了一个jQuery插件,它允许您以各种方式进行PHP函数调用:https://github.com/Xaxis/jquery.php
简单示例用法:
// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]