php - 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 ?
解决方案
您可以将每个路径的代码放在不同的函数中,并使用关联数组来调用它们。
$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]();
}
}
推荐阅读
- java - SpringBoot、Hibernate 和 flyway db 问题
- c# - PropertyChanged 和 IValueConverter
- java - 正则表达式不应包含整个单词和点
- php - 注册一个自定义的 symfony 控制台命令,使其在“建议命令”列表中可用
- javascript - 带箱线图的 highcharts 雷达图
- java - 在 Android 应用程序中添加关于 Java 部分的意图时出错
- regex - 有没有办法使用 NiFi 将两个 CSV 内容合并为一个 CSV
- excel - 使用 Shape.Copy 时的 Excel VBA 运行时错误 -2147221040
- oauth - 如何在 OpenAM 12 中更改访问令牌的生命周期
- swift - 斯威夫特:反斜杠点“\”是什么意思?意思是?