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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度