繁体   English   中英

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

[英]calling php functions from javascript, onload (AJAX?)

我已经搜索了将近一个小时,但没有找到解决该问题的合适示例:我想调用PHP函数(这是与页面加载时执行的javascript函数给出的路径的简单取消链接)。 我对AJAX一点也不擅长,我想了解如何从javascript代码直接调用index.php文件中包含的PHP函数。

这是我的javascript代码段中的内容:

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

您发送函数名称(以防将来会有更多功能),并将参数作为获取参数

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

在您的PHP脚本上,您应该处理它:

<?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
?>

您不能直接通过ajax调用来调用php函数,它只会像从浏览器中打开页面index.php一样调用php脚本。

您必须在php脚本中添加测试以知道必须调用哪个函数,例如。

如果您调用ajax,则页面/dev/templates/absolu/index.php?mode=delete_image&image=filename.png

<?php
if($_GET['mode'] == "delete_image") {
    unlink($_GET['image']);
}
?>

请注意任何人都可以调用此页面,因此您必须检查要删除的内容并验证在GET参数中收到的内容。 在这里,我可以调用/dev/templates/absolu/index.php?mode=delete_image&image=index.php删除php脚本页面。

使用jquery(http://jquery.com/),您可以按以下方式进行调用:

$(document).ready(function() {
  $.get("/dev/templates/absolu/index.php?", {
    'action': 'delete',
    'other': 'get-parameters',
    'r': Math.random()
  });
});

服务器端示例:

<?php

switch( $_GET['action'] ) {
  case 'delete': 
    // call unlink here
  break;
  case 'dosomething':
    // else
  break;
  default: 
    // Invalid request
  break;
}

请注意,删除文件应负责任地处理(强制执行安全检查),以确保不会错误或故意删除错误的文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM