Jas*_*ell 76 html javascript php ajax
有没有办法通过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>
Run Code Online (Sandbox Code Playgroud)
我基本上想运行php函数query("hello")
,当我点击名为"Test"的href时会调用php函数.
Chr*_*ker 142
从本质上讲,这就是AJAX的用途.您的页面加载,并向元素添加事件.当用户触发事件时,例如通过单击某些内容,您的Javascript使用XMLHttpRequest对象向服务器发送请求.
在服务器响应之后(可能是输出),另一个Javascript函数/事件为您提供了一个处理该输出的位置,包括简单地将其粘贴到页面中,就像任何其他HTML一样.
你可以使用普通的Javascript"手动"完成它,或者你可以使用jQuery.根据项目的大小和特定情况,使用普通的Javascript可能更简单.
在这个非常基本的示例中,我们向myAjax.php
用户点击链接时发送请求.服务器将生成一些内容,在本例中为"hello world!".我们将使用id放入HTML元素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;
}
Run Code Online (Sandbox Code Playgroud)
HTML
<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>
Run Code Online (Sandbox Code Playgroud)
PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
Run Code Online (Sandbox Code Playgroud)
尝试一下: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;
}
Run Code Online (Sandbox Code Playgroud)
尝试一下:http://jsfiddle.net/GRMule/WQXXT/
暂时不要急于使用jQuery:添加任何库仍然会为您的项目添加数百或数千行代码,就像您编写它们一样.在jQuery库文件中,您将找到与第一个示例中类似的代码,以及更多内容.这可能是件好事,也可能不是.计划并考虑项目的当前规模和未来扩展的可能性以及目标环境或平台.
如果这就是你需要做的全部,那就写一下普通的javascript,你就完成了.
文档
XMLHttpRequest
在MDN上 - https://developer.mozilla.org/en/XMLHttpRequestXMLHttpRequest
在MSDN上 - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspxjQuery.ajax
- http://api.jquery.com/jQuery.ajax/Dor*_*Dor 15
PHP在服务器上进行评估; javascript在客户端/浏览器中进行评估,因此您无法直接从javascript调用PHP函数.但您可以使用AJAX向服务器发出HTTP请求,该服务器将激活PHP函数.
mor*_*sik 11
从JS执行PHP的唯一方法是AJAX.您可以将数据发送到服务器(例如,GET /ajax.php?do=someFunction),然后在ajax.php中写入:
function someFunction() {
echo 'Answer';
}
if ($_GET['do'] === "someFunction") {
someFunction();
}
Run Code Online (Sandbox Code Playgroud)
然后,用JS捕捉答案(我使用jQuery来制作AJAX请求)
可能你需要一些格式的答案.请参阅JSON或XML,但JSON易于使用JavaScript.在PHP中,您可以使用函数json_encode($ array); 将数组作为参数.
我最近发布了一个 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/"]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
268151 次 |
最近记录: |