从 JavaScript 调用 php 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7165395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call php function from JavaScript
提问by Jason Russell
Is there a way I can run a php function through a JS function?
有没有办法通过 JS 函数运行 php 函数?
something like this:
像这样:
<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>
I basically want to run the php function query("hello")
, when I click on the href called "Test" which would call the php function.
我基本上想运行 php 函数query("hello")
,当我单击称为“Test”的 href 时,它将调用 php 函数。
回答by Chris Baker
This is, in essence, what AJAXis for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest objectto send a request to a server.
本质上,这就是AJAX的用途。您的页面加载,并向元素添加一个事件。当用户触发事件时,比如通过单击某物,您的 Javascript 使用XMLHttpRequest 对象向服务器发送请求。
After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.
在服务器响应(大概是输出)之后,另一个 Javascript 函数/事件为您提供了一个处理该输出的地方,包括像任何其他 HTML 一样简单地将其粘贴到页面中。
You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .
您可以使用普通的 Javascript 来“手工”完成,也可以使用 jQuery。根据项目的大小和特定情况,使用普通的 Javascript 可能更简单。
Plain Javascript
纯Javascript
In this very basic example, we send a request to myAjax.php
when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output
.
在这个非常基本的例子中,我们myAjax.php
在用户点击链接时发送一个请求。服务器将生成一些内容,在本例中为“hello world!”。我们将放入带有 id 的 HTML 元素output
。
The javascript
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;
}
The HTML
HTML
<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>
The PHP
PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
Try it out: http://jsfiddle.net/GRMule/m8CTk/
试试看:http: //jsfiddle.net/GRMule/m8CTk/
With a javascript library (jQuery et al)
使用 javascript 库(jQuery 等)
Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.
可以说,这是很多 Javascript 代码。当然,您可以通过收紧块或使用更简洁的逻辑运算符来缩短它,但是那里还有很多事情要做。如果您计划在您的项目中做很多此类事情,那么使用 javascript 库可能会更好。
Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:
使用与上面相同的 HTML 和 PHP,这是您的整个脚本(页面中包含 jQuery)。为了与 jQuery 的一般风格更加一致,我稍微收紧了代码,但你明白了:
// handles the click event, sends the query
function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
Try it out: http://jsfiddle.net/GRMule/WQXXT/
试试看:http: //jsfiddle.net/GRMule/WQXXT/
Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.
暂时不要急于使用 jQuery:添加任何库仍然会向您的项目添加数百或数千行代码,就像您编写它们一样。在 jQuery 库文件中,您会发现与第一个示例中的代码类似的代码,以及更多的. 这可能是一件好事,也可能不是。计划并考虑项目的当前规模和未来扩展的可能性以及目标环境或平台。
If this is all you need to do, write the plain javascript once and you're done.
如果这就是您需要做的全部,那么编写一次普通的 javascript 就完成了。
Documentation
文档
- AJAXon MDN - https://developer.mozilla.org/en/ajax
XMLHttpRequest
on MDN - https://developer.mozilla.org/en/XMLHttpRequestXMLHttpRequest
on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx- jQuery - http://jquery.com/download/
jQuery.ajax
- http://api.jquery.com/jQuery.ajax/
- MDN 上的AJAX- https://developer.mozilla.org/en/ajax
XMLHttpRequest
在 MDN 上 - https://developer.mozilla.org/en/XMLHttpRequestXMLHttpRequest
在 MSDN 上 - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx- jQuery - http://jquery.com/download/
jQuery.ajax
- http://api.jquery.com/jQuery.ajax/
回答by Dor
PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.
PHP 在服务器端进行评估;javascript 在客户端/浏览器上进行评估,因此您不能直接从 javascript 调用 PHP 函数。但是您可以使用 AJAX 向将激活 PHP 函数的服务器发出 HTTP 请求。
回答by morsik
The only way to execute PHP from JS is AJAX. You can send data to server (for eg, GET /ajax.php?do=someFunction) then in ajax.php you write:
从 JS 执行 PHP 的唯一方法是 AJAX。您可以将数据发送到服务器(例如,GET /ajax.php?do=someFunction)然后在 ajax.php 中编写:
function someFunction() {
echo 'Answer';
}
if ($_GET['do'] === "someFunction") {
someFunction();
}
and then, catch the answer with JS (i'm using jQuery for making AJAX requests)
然后,用 JS 找到答案(我正在使用 jQuery 进行 AJAX 请求)
Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.
可能您需要某种格式的答案。请参阅 JSON 或 XML,但 JSON 易于与 JavaScript 一起使用。在 PHP 中你可以使用函数 json_encode($array); 获取数组作为参数。
回答by Xaxis
I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php
我最近发布了一个 jQuery 插件,它允许您以各种方式进行 PHP 函数调用:https: //github.com/Xaxis/jquery.php
Simple example usage:
简单示例用法:
// 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 ); // ["$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]