对我而言,这是一个新的东西,所以我只是研究这个并试图理解它.正如您在php脚本中看到的那样,有两个函数,我试图用jquery调用一个特定的函数.
现在,如果我有一个功能,那么我可以做到,但是当我有2个或更多时,我开始卡住了.我想,当我有2个函数时,我可以做到这一点,但是只要有更多的变量在运行或更多的函数,我只是在我的php中制作大量的if语句?
问题是,当我附加数据库时,我需要考虑可能发生的所有输入. 使用jquery&ajax时如何指定特定的php函数?
//function.php
<?php
function firstFunction($name)
{
echo "Hello - this is the first function";
}
function secondFunction($name)
{
echo "Now I am calling the second function";
}
?>
<?php
$var = $_POST['name'];
if(isset($var))
{
$getData = firstFunction($var);
}
else if(isset($var))
{
$getData = secondFunction($var);
}
else
{
echo "No Result";
}
?>
//index.html
<div id="calling">This text is going to change></div>
<script>
$(document).ready(function() {
$('#calling').load(function() {
$.ajax({
cache: false,
type: "POST",
url: "function.php",
data: 'name=myname'
success: function(msg)
{
$('#calling').html((msg));
}
}); // Ajax Call
}); //event handler
}); //document.ready
</script>
Run Code Online (Sandbox Code Playgroud)
Rob*_*ill 11
您需要通过数据对象或URL上的GET变量传入参数.或者:
url: "function.php?action=functionname"
Run Code Online (Sandbox Code Playgroud)
要么:
data: {
name: 'myname',
action: 'functionname'
}
Run Code Online (Sandbox Code Playgroud)
然后在PHP中,您可以访问该属性并处理它:
if(isset($_POST['action']) && function_exists($_POST['action'])) {
$action = $_POST['action'];
$var = isset($_POST['name']) ? $_POST['name'] : null;
$getData = $action($var);
// do whatever with the result
}
Run Code Online (Sandbox Code Playgroud)
注意:出于安全原因,更好的想法是将可以调用的可用函数列入白名单,例如:
switch($action) {
case 'functionOne':
case 'functionTwo':
case 'thirdOKFunction':
break;
default:
die('Access denied for this function!');
}
Run Code Online (Sandbox Code Playgroud)
实施示例:
// PHP:
function foo($arg1) {
return $arg1 . '123';
}
// ...
echo $action($var);
// jQuery:
data: {
name: 'bar',
action: 'foo'
},
success: function(res) {
console.log(res); // bar123
}
Run Code Online (Sandbox Code Playgroud)