weixin_33724059 2014-11-25 20:16 采纳率: 0%
浏览 23

Ajax中的PHP传递参数

In my PHP file I have a variable $file = "abc". How would I create a button in HTML to run a function in PHP passing in $file as an argument? I saw that I need to do this using jQuery/AJAX. For the sake of simplicity, let's just say I want to echo $file.

HTML/JS

<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.js"></script>
<input type="submit" class="button" name="Del" value="Del" />
<script type="text/javascript">
$(document).ready(function(){
    $('.button').click(function(){
        var clickBtnValue = $(this).val();
        var ajaxurl = 'ajax.php',
        data =  {'action': clickBtnValue};
        $.post(ajaxurl, data, function (response) {
            console.log(response);
            //alert("action performed successfully");
        });
    });

});
</script>

ajax.php

<?php
if (isset($_POST['action'])) {
    Del();
}

function Del($file) {
    echo $_POST['action'];
    echo $file;
    exit;
}
?>

I am unsure of how to modify this to pass in a php argument ($file) through AJAX.

  • 写回答

2条回答 默认 最新

  • 七度&光 2014-11-25 20:33
    关注

    In your HTML/JS:

    data =  {'action': clickBtnValue, 'file' : '<?php echo $file?>'};
    

    In your ajax.php:

    if (isset($_POST['action'])) {
        Del($_POST['file']);
    }
    

    This is a very simple example but you can probably adapt it to your needs. Note that there are a ton of potential security implications with this approach, depending on what you're actually doing, so be careful and clean any input in $_POST.

    评论

报告相同问题?