繁体   English   中英

如何通过ajax请求加载服务器端功能?

[英]How to load serverside function by ajax-request?

我问自己是否可以通过Ajax-Request在一个PHP文件中加载关联的PHP函数。 当然有可能,但是如何呢?

通常,在我的Web应用程序中,每个Ajax函数(在客户端)都通过URL调用特定的PHP文件。 例如,此Ajax调用include / ajax.php。

function ajaxRequest( ) {

    $( ".loading-overlay" ).show();
    $('#loading').show();
    $.ajax({
        url : "includes/ajax.php",
        type : "POST",
        data : $("#nodes").serialize(),
        dataType: "json",
        cache : false,
        success: function( data ) {
            drawChart( data.chart_data );
            currentGauge( data.current_data.current );
            tableMaxMin( data.maxmin_data );
            tableAvgDays( data.avg_data );
            $('#loading').hide();
            $( ".loading-overlay" ).hide();
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nERROR: "+ err);
        }
    });
}

我的大多数应用程序都具有一个以上的Ajax请求。 我认为效率不是很高,特别是为每个ajax函数创建一个新的PHP文件时会感到困惑。 更好的解决方案是将每个不同的(服务器端)响应引擎存储在一个具有不同功能的PHP文件中。

仅出于理解,我正在寻找类似这样的东西:

function ajaxRequest( ) {

    $( ".loading-overlay" ).show();
    $('#loading').show();
    $.ajax({
        url : "includes/ajax.php",
        function: parseData(),  //<--- This is not allowed
        type : "POST",
        data : $("#nodes").serialize(),
        dataType: "json",
        cache : false,
        success: function( data ) {
            drawChart( data.chart_data );
            currentGauge( data.current_data.current );
            tableMaxMin( data.maxmin_data );
            tableAvgDays( data.avg_data );
            $('#loading').hide();
            $( ".loading-overlay" ).hide();
        },
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nERROR: "+ err);
        }
    });
}

那么,如何通过函数而不是通过URL加载特定的响应引擎呢?

来自一个文件的ajax调用

$.ajax({
    url: "includes/ajax.php?action=login",
    method: "POST",
    success: function(response){
        console.log(response);
    }
})

来自另一个文件的ajax调用

$.ajax({
    url: "includes/ajax.php?action=userdetail",
    method: "POST",
    data : {'userId': 1},
    success: function(response){
        console.log(response);
    }
});

//ajax.php

<?php

    $action = $_GET['action'];
    extract($_POST);
    switch($action){
        case 'login' :
            //code for login
        break;
        case 'userdetail' :
            //code for userdetail you can use directly $userId to access post variable as we have use `extract` method.
        break;
        default :
             echo json_encode(array("message"=>"Please provide proper action"));
        break;
    }
?>

暂无
暂无

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

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