PHP Function with jQuery AJAX?


PHP Function with jQuery AJAX?

我有一个关于PHP函数,jQuery和AJAX的问题。如果我在php索引中有这样一个按钮:

    <input type="submit" value="Download" id="download"/>

我有另一个php文件(dubs。php)包含这个

<?php
function first(){
    echo 'first';
}
function second(){
    echo 'second';  
}
?>

和我的jQuery,像这样:

$(document).ready(function(e) {
    $("#download").click(function(){
        $.ajax({
            type: "GET",
            url: "dubs.php",
        });
    });
});

我如何告诉我的AJAX请求选择例如第二个函数?

我不知道如何做到这一点,我已经尝试过"success: first()""success: function(){ first() }",但没有工作。

在你的ajax传递一些参数来确定你想要使用的函数,像这样

    $("#download").click(function(){
        $.ajax({
            type   : "POST",//If you are using GET use $_GET to retrive the values in php
            url    : "dubs.php",
            data   : {'func':'first'},
            success: function(res){
              //Do something after successfully completing the request if required
            },
            error:function(){
              //If some error occurs catch it here
            }
        });
    });

在php文件

您可以检索data通过ajax发送的值,并执行以下操作

if(isset($_POST['func']) && $_POST['func']=='first'){
    first();
}
else{
    second();
}

我要这样做:

PHP:

<?php
function first(){
    echo 'first';
}
function second(){
    echo 'second';  
}

  if (isset($_POST["first"])) first();
  if (isset($_POST["second"])) second(); //add 'else' if needed
?>
jQuery:

$.post("dubs.php", {"first":true}, function(result) {
  $("#someDivToShowText").text(result);
});

然后,根据您发送给$.post的对象,php文件将知道运行哪个函数。

在您的PHP页面中试试:

<?php
function first(){
    echo 'first';
}
function second(){
    echo 'second';  
}
switch($_POST['func']) {
    case "first":
    first();
    break;
    case "second":
    second();
    break;
    default:
    // Define your default here }
?>

和这个在你的JS:

$(document).ready(function(e) {
    $("#download").click(function(){
        $.ajax({
            type: "GET",
            url: "dubs.php",
            data: {'func':'first'}
        });
    });

func变量将告诉php运行哪个函数!

});

为什么不尝试通过data:{func:f1}并将其放在php端,如果f1在那里,则触发第一个函数。虽然你可以发送多个:

jQuery:

$("#download").click(function(e){
    e.preventDefault(); // <----stops the page refresh
    $.ajax({
        type: "GET",
        url: "dubs.php",
        data:{'func':'f1'}
    });
});
PHP:

<?php
  function first(){
     echo 'first';
  }
  function second(){
     echo 'second';  
  }

if(isset($_GET['func']=='f1'){
     first();
}else{
     second();
}
?>

JS

$("#download").click(function(){
    $.ajax({
        type: "GET",
        url: "dubs.php",
        data: {'function':'first'}
    });
});


PHP

call_user_func($_GET['function']);


注意
注意$_GET参数,最好先检查$_GET

的内容