dongyu2764 2012-06-26 13:51
浏览 154
已采纳

从javascript,onload调用php函数(AJAX?)

I have been searching for almost an hour without finding proper example to fix my problem: I would like to call a PHP function (it's a simple unlink with the path given from a javascript function that's executed on page load). I am not good at all with AJAX and I would like to understand how to call directly the PHP function, contained in the index.php file, from the javascript code.

Here's what I have in my javascript code snippet:

var xmlhttp;

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/dev/templates/absolu/index.php?s=" + Math.random(),true);
//@unlink(listeImages[i].toString());
  • 写回答

3条回答 默认 最新

  • drjyvoi734793 2012-06-26 13:59
    关注

    You send the function name (in case you will have more functions in the future) and params as get params

    var fileToDelete;
    var xmlhttp;
    
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET","/dev/templates/absolu/index.php?s=" + Math.random()+"&action=delete&file="+fileToDelete,true);
    

    On your PHP script, you should handle it:

    <?php
    if (isset($_GET['action'])){
      switch($_GET['action']){  
         case 'delete':
           @unlink(listeImages[$_GET['action']].toString());
         break;
         //Other functions you may call
      }
      exit;
    }
    //The rest of your index.php code
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作