2014-09-10 34 views
0

嗨我有一种情况一定PHP函数,

我想使用AJAX $不用彷徨方式来指定在一个单独的PHP文件用特定的PHP函数。我对语法不太确定。

JavaScript的

function all(){ 

    $.get({ 
    url: "functions.php THEN GET A CERTAIN FUNCTION ", 
    success: function success(data){ paint(data) }, 
    dataType: "html" 
    }); 


}); 

function.php

<?php 

function helloWorld(){ 

echo "Hello World"; 

}; 

    function helloMars(){ 

echo "Hello Mars"; 

}; 

任何帮助,不胜感激

+0

你需要做的是以某种方式表明你想触发某个功能。可能在查询中。然后使用一些逻辑:'if/else'或'switch'并检测是否设置了触发器。如果是,请致电您的功能。 – Crackertastic 2014-09-10 17:28:25

+0

url:“functions.php?fname = helloWorld”, – 2014-09-10 17:28:45

回答

1

传递一个变量在data属性或URL查询字符串,并在你的PHP脚本,选择基于该变量的函数。

$.get({ 
    url: "functions.php", 
    data: { "vname": "something" }, 
    success: function success(data){ paint(data) }, 
    dataType: "html" 
}); 

http://api.jquery.com/jquery.get/

PHP:

if ($_GET["vname"] == "something") { 
    helloWorld(); 
} else { 
    helloMars(); 
} 

http://php.net/manual/en/reserved.variables.get.php

+0

如果vname是函数的名称,则不必使用if/else。 $ VNAME = $ _ GET [ 'VNAME']; $ VNAME(); – 2014-09-10 17:32:48

+2

这看起来像是一个潜在的安全漏洞给我。如果他们猜出正确的名字,有人可能会执行一个你不想执行的函数。 – Blazemonger 2014-09-10 17:36:24

+0

因为我们不知道这是否与直接用户输入有关,所以我们不能肯定地说。我认为值得注意的是函数可以用变量调用。同样在你的代码中,如果“猜测”的人只是猜测helloMars将始终执行的任何事情。我认为这并不理想。 – 2014-09-10 17:40:18

0

愿这帮助你

$.get("test-ajax.php",function(data,status){ 

    $(".content").html(data); 

}); 

“测试ajax.php” 文件

function helloWorld()

{ echo "hello world"; }

function helloMars() {

echo "Hello Mars";

}

helloWorld(); helloMars();