dongxi2014 2010-01-22 15:46
浏览 66
已采纳

如何使用Ajax使用URL或其他方法注入特定的PHP函数?

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.

let says I have a div called #divName.

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);
     }
   }

The I have my fileName.php file:

<?php

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

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

?>

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

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.

Any help would be appreciated!

  • 写回答

3条回答 默认 最新

  • dpl3350 2010-01-22 15:51
    关注

    Try with:

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

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要