如何使用Ajax来使用URL,或其他方式注入具体的PHP函数? [英] How to use Ajax to inject specific PHP function using URL, or other method?

查看:83
本文介绍了如何使用Ajax来使用URL,或其他方式注入具体的PHP函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从刚才的JS到PHP和Ajax的境界感动。我已经在过去涉足一些与PHP。 我的真正的AP preciate多少帮助计算器一直在帮助我的基本问题。

I'm moving from the realm of just JS to php and Ajax. I've dabbled some with PHP in the past. I really appreciate how much help stackoverflow has been in helping me with basic questions.

让说我有一个名为DIV #divName

let says I have a div called #divName.

我使用Ajax的以下JS。一些这只是伪code。

I use the following JS for Ajax. Some of this is just pseudo code.

var request = false;
   try {
     request = new XMLHttpRequest();
   } catch (trymicrosoft) {
     try {
       request = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (othermicrosoft) {
       try {
         request = new ActiveXObject("Microsoft.XMLHTTP");
       } catch (failed) {
         request = false;
       }  
     }
   }

   if (!request)
     alert("Error initializing XMLHttpRequest!");

   function getAjaxInfo(<name of the php function???>) { //<<<<< this is the function I need help with
    var myFunction= nameOfPHPfunctionIJustGot;
     var url = "filename.php?func=" + myFunction;
     request.open("GET", url, true);
     request.onreadystatechange = updatePage;
     request.send(null);
   }

  function updatePage() {
     if (request.readyState == 4) {
       if (request.status == 200) {
         var response = request.responseText;
             document.getElementById("divName").innerHTML = response; //probably going to use Jquery append here, but this example works.
               } else
         alert("status is " + request.status);
     }
   }

在我有我的fileName.php文件:

The I have my fileName.php file:

<?php

function header() { ?>
   header content goes here
<?php }

function footer() { ?>
    footer content goes here
<?php }

?>

我的目标是,当我执行 getAjaxInfo(),我可以拉什么PHP函数我想要的。

My goal is that when I execute getAjaxInfo(), I can pull whatever PHP function I want.

因此​​,可以说,如果我做了的onClick =getAjaxInfo(头)将得到PHP的头功能,适用于JavaScript函数,然后应用以一个div。

So lets say if I do a onClick="getAjaxInfo(header)" it will get the php header function, apply it to a javascript function, and then apply that to a div.

任何帮助将是AP preciated!

Any help would be appreciated!

推荐答案

尝试使用:

$func=$_GET['func'];
if(function_exists($func)) $func();

在这种方式,您获得通过GET传递函数名和执行它。

In this way you get the function name passed by GET and the execute it.

如果您希望能够调用只有特定的功能:

If you want to be able to call only certain functions:

$allowedFunctions=array("header","footer");
$func=$_GET['func'];
if(in_array($func,$allowedFunctions) && function_exists($func)) $func();

这篇关于如何使用Ajax来使用URL,或其他方式注入具体的PHP函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆