如何通过 JavaScript 调用 PHP 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15757750/
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
How can I call PHP functions by JavaScript?
提问by wallgeek
I am trying to call a PHP function from an external PHP file into a JavaScript script. My code is different and large, so I am writing a sample code here.
我正在尝试从外部 PHP 文件调用 PHP 函数到 JavaScript 脚本中。我的代码不同而且很大,所以我在这里写了一个示例代码。
This is my PHP code:
这是我的 PHP 代码:
<?php
function add($a,$b){
$c=$a+$b;
return $c;
}
function mult($a,$b){
$c=$a*$b;
return $c;
}
function divide($a,$b){
$c=$a/$b;
return $c;
}
?>
This is my JavaScript code:
这是我的 JavaScript 代码:
<script>
var phpadd= add(1,2); //call the php add function
var phpmult= mult(1,2); //call the php mult function
var phpdivide= divide(1,2); //call the php divide function
</script>
So this is what I want to do.
所以这就是我想要做的。
My originalPHP file doesn't include these mathematical functions but the idea is same.
我的原始PHP 文件不包含这些数学函数,但想法是相同的。
If some how it doesn't have a proper solution, then may you pleasesuggest an alternative, but it should call values from external PHP.
如果某些方法没有合适的解决方案,那么请您提出替代方案,但它应该从外部 PHP 调用值。
回答by Victor
Yes, you can do ajax request to server with your data in request parameters, like this (very simple):
是的,您可以使用请求参数中的数据向服务器发出ajax请求,如下所示(非常简单):
Note that the following code uses jQuery
请注意,以下代码使用了jQuery
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
and your_functions_address.php like this:
和 your_functions_address.php 像这样:
<?php
header('Content-Type: application/json');
$aResult = array();
if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }
if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }
if( !isset($aResult['error']) ) {
switch($_POST['functionname']) {
case 'add':
if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
$aResult['error'] = 'Error in arguments!';
}
else {
$aResult['result'] = add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1]));
}
break;
default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
echo json_encode($aResult);
?>
回答by Sandeep Kapil
Try This
尝试这个
<script>
var phpadd= <?php echo add(1,2);?> //call the php add function
var phpmult= <?php echo mult(1,2);?> //call the php mult function
var phpdivide= <?php echo divide(1,2);?> //call the php divide function
</script>
回答by Anitha Mani
use document.write for example,
使用 document.write 例如,
<script>
document.write(' <?php add(1,2); ?> ');
document.write(' <?php milt(1,2); ?> ');
document.write(' <?php divide(1,2); ?> ');
</script>
回答by Romain Durand
You need to create an API : Your js functions execute AJAX requests on your web service
您需要创建一个 API:您的 js 函数在您的 Web 服务上执行 AJAX 请求
var mult = function(arg1, arg2)
$.ajax({
url: "webservice.php?action=mult&arg1="+arg1+"&arg2="+arg2
}).done(function(data) {
console.log(data);
});
}
on the php side, you'll have to check the action parameter in order to execute the propre function (basically a switch statement on the $_GET["action"] variable)
在 php 方面,您必须检查 action 参数才能执行 propre 函数(基本上是 $_GET["action"] 变量上的 switch 语句)
回答by Hernaldo Gonzalez
index.php
索引.php
<body>
...
<input id="Div7" name="Txt_Nombre" maxlenght="100px" placeholder="Nombre" />
<input id="Div8" name="Txt_Correo" maxlenght="100px" placeholder="Correo" />
<textarea id="Div9" name="Txt_Pregunta" placeholder="Pregunta" /></textarea>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".Txt_Enviar").click(function() { EnviarCorreo(); });
});
function EnviarCorreo()
{
jQuery.ajax({
type: "POST",
url: 'servicios.php',
data: {functionname: 'enviaCorreo', arguments: [$(".Txt_Nombre").val(), $(".Txt_Correo").val(), $(".Txt_Pregunta").val()]},
success:function(data) {
alert(data);
}
});
}
</script>
servicios.php
服务.php
<?php
include ("correo.php");
$nombre = $_POST["Txt_Nombre"];
$correo = $_POST["Txt_Corro"];
$pregunta = $_POST["Txt_Pregunta"];
switch($_POST["functionname"]){
case 'enviaCorreo':
EnviaCorreoDesdeWeb($nombre, $correo, $pregunta);
break;
}
?>
correo.php
相关文件
<?php
function EnviaCorreoDesdeWeb($nombre, $correo, $pregunta)
{
...
}
?>
回答by Naresh
I wrote some script for me its working .. I hope it may useful to you
我为我写了一些脚本它的工作..我希望它对你有用
<?php
if(@$_POST['add'])
{
function add()
{
$a="You clicked on add fun";
echo $a;
}
add();
}
else if (@$_POST['sub'])
{
function sub()
{
$a="You clicked on sub funn";
echo $a;
}
sub();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<input type="submit" name="add" Value="Call Add fun">
<input type="submit" name="sub" Value="Call Sub funn">
<?php echo @$a; ?>
</form>
回答by Naresh
This work perfectly for me:
这项工作非常适合我:
To call a PHP function (with parameters too) you can, like a lot of people said, send a parameter opening the PHP file and from there check the value of the parameter to call the function. But you can also do that lot of people say it's impossible: directly call the proper PHP function, without adding code to the PHP file.
要调用 PHP 函数(也带有参数),您可以像很多人所说的那样,发送一个参数打开 PHP 文件,然后从那里检查参数的值以调用该函数。但是你也可以做到很多人说不可能的:直接调用合适的PHP函数,而不用在PHP文件中添加代码。
I found a way:
我找到了一个方法:
This for JavaScript:
这对于 JavaScript:
function callPHP(expression, objs, afterHandler) {
expression = expression.trim();
var si = expression.indexOf("(");
if (si == -1)
expression += "()";
else if (Object.keys(objs).length > 0) {
var sfrom = expression.substring(si + 1);
var se = sfrom.indexOf(")");
var result = sfrom.substring(0, se).trim();
if (result.length > 0) {
var params = result.split(",");
var theend = expression.substring(expression.length - sfrom.length + se);
expression = expression.substring(0, si + 1);
for (var i = 0; i < params.length; i++) {
var param = params[i].trim();
if (param in objs) {
var value = objs[param];
if (typeof value == "string")
value = "'" + value + "'";
if (typeof value != "undefined")
expression += value + ",";
}
}
expression = expression.substring(0, expression.length - 1) + theend;
}
}
var doc = document.location;
var phpFile = "URL of your PHP file";
var php =
"$docl = str_replace('/', '\\', '" + doc + "'); $absUrl = str_replace($docl, $_SERVER['DOCUMENT_ROOT'], str_replace('/', '\\', '" + phpFile + "'));" +
"$fileName = basename($absUrl);$folder = substr($absUrl, 0, strlen($absUrl) - strlen($fileName));" +
"set_include_path($folder);include $fileName;" + expression + ";";
var url = doc + "/phpCompiler.php" + "?code=" + encodeURIComponent(php);
$.ajax({
type: 'GET',
url: url,
complete: function(resp){
var response = resp.responseText;
afterHandler(response);
}
});
}
This for a PHP file which isn't your PHP file, but another, which path is written inurl
variable of JS functioncallPHP
, and it's required to evaluate PHP code. This file is called 'phpCompiler.php'and it's in the root directory of your website:
这是一个 PHP 文件,它不是你的 PHP 文件,而是另一个,它的路径写在url
JS 函数的变量中callPHP
,并且需要评估 PHP 代码。该文件名为“phpCompiler.php”,位于您网站的根目录中:
<?php
$code = urldecode($_REQUEST['code']);
$lines = explode(";", $code);
foreach($lines as $line)
eval(trim($line, " ") . ";");
?>
So, your PHP code remain equals except return values, which will be echoed:
因此,除了返回值之外,您的 PHP 代码保持相等,返回值将被回显:
<?php
function add($a,$b){
$c=$a+$b;
echo $c;
}
function mult($a,$b){
$c=$a*$b;
echo $c;
}
function divide($a,$b){
$c=$a/$b;
echo $c;
}
?>
I suggest you to remember that jQuery is required:
Download it from Google CDN:
我建议你记住 jQuery 是必需的:
从 Google CDN 下载它:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
or from Microsoft CDN: "I prefer Google! :)"
或来自 Microsoft CDN:“我更喜欢谷歌!:)”
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
Better is to download the file from one of two CDNs and put it as local file, so the startup loading of your website's faster!
更好的是从两个 CDN 之一下载文件并将其作为本地文件,这样您网站的启动加载速度会更快!
The choice is to you!
选择权在你!
Now you finished! I just tell you how to use现在你完成了!我只是告诉你怎么用
callPHP
callPHP
function. This is the JavaScript to call PHP:功能。这是调用 PHP 的 JavaScript://Names of parameters are custom, they haven't to be equals of these of the PHP file.
//These fake names are required to assign value to the parameters in PHP
//using an hash table.
callPHP("add(num1, num2)", {
'num1' : 1,
'num2' : 2
},
function(output) {
alert(output); //This to display the output of the PHP file.
});
回答by Lemon Drop
If you actually want to send data to a php script for example you can do this:
例如,如果您确实想将数据发送到 php 脚本,则可以执行以下操作:
The php:
php:
<?php
$a = $_REQUEST['a'];
$b = $_REQUEST['b']; //totally sanitized
echo $a + $b;
?>
Js (using jquery):
Js(使用jquery):
$.post("/path/to/above.php", {a: something, b: something}, function(data){
$('#somediv').html(data);
});
回答by radmen
回答by perlesvaus
I created this library JS PHP Importwhich you can download from github, and use whenever and wherever you want.
我创建了这个库JS PHP Import,你可以从 github 下载它,随时随地使用。
The library allows importing php functions and class methods into javascript browser environment thus they can be accessed as javascript functions and methods by using their actual names. The code uses javascript promises so you can chain functions returns.
该库允许将 php 函数和类方法导入 javascript 浏览器环境,因此可以使用它们的实际名称作为 javascript 函数和方法访问它们。该代码使用 javascript 承诺,因此您可以链接函数返回。
I hope it may useful to you.
我希望它对你有用。
Example:
例子:
<script>
$scandir(PATH_TO_FOLDER).then(function(result) {
resultObj.html(result.join('<br>'));
});
$system('ls -l').then(function(result) {
resultObj.append(result);
});
$str_replace(' ').then(function(result) {
resultObj.append(result);
});
// Chaining functions
$testfn(34, 56).exec(function(result) { // first call
return $testfn(34, result); // second call with the result of the first call as a parameter
}).exec(function(result) {
resultObj.append('result: ' + result + '<br><br>');
});
</script>