首页 > 解决方案 > Load html from external file via ajax

问题描述

I need in my project to load some html from external file like you see in below code this my php code

if(strtolower($_SERVER["request_method"]) == "get") {
    $html = "";
    $path = $_GET["path"];
    if($path == "cities-select-options") {
        $country_code = htmlspecialchars($_GET["country_code"]);
        $get_cities = get_cities($country_code);
        $html .= ' <option value=""> --- </option> ';
        foreach($get_cities as $city):
            $html .= ' <option value="">'.$city["city_name"].'</option> ';
        endforeach;
        echo $html;
    }elseif() {
        /* */
    }
}

and this my js code

$( "#ad_country" ).on("change",function() {
    $country_id = $(this).val();
    $.get("htmlLoader.php?path=cities-select-option&country_id="+$country_id,function(html) {
        $("#ad_city").html(html);
    });
});

but I'm confused by this method. because I have too many section need to be load via ajax. So my question is : there is way to do that without writing many if conditions ?

标签: phpajax

解决方案


您可以将每个路径的代码放在不同的函数中,并使用关联数组来调用它们。

$paths = array(
    'cities-select-option' => 'get_cities_options',
    'states-select-option' => 'get_states_options',
    ...
);

function get_cities_options() {
    $html = ' <option value=""> --- </option> ';
    $country_code = $_GET["country_code"];
    $get_cities = get_cities($country_code);
    foreach($get_cities as $city):
        $html .= ' <option value="">'.$city["city_name"].'</option> ';
    endforeach;
    return $html;
}

function get_states_options() {
    ...
}

if (strtolower($_SERVER['REQUEST_METHOD'] == 'get') {
    $path = $_GET['path'];
    if (isset($paths[$path])) {
        echo $paths[$path]();
    }
}

推荐阅读