dqi*_*qiu 3 javascript jquery codeigniter
我编写了下面的例程,根据我的codeigniter应用程序选择的国家/地区检索城市.
$(document).ready(function() {
$("select#cbo_country").change(function() {
$.post("http://localhost/main/index.php/city/get_data_by_country", {
int_country_id : $(this).val()
},
function(data) {
// some code here
},'json');
})
});
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我对网址进行了硬编码(http://localhost/main/index.php/city/get_data_by_country),我知道这是一个不好的做法,但我无法帮助它.
有没有一个很好的干净方法来不硬编码网址?我以前使用codeigniter的base_url(),但由于我将例程移动到js文件,我不再能够使用该函数.
Mat*_*att 10
(主要)从我的答案中获取如何在Javascript中获取相对路径?.
你有两个选择:
在JavaScript中构建配置/首选项对象,其中包含所有特定于环境的设置:
var config = {
base: "<?php echo base_url(); ?>",
someOtherPref: 4
};
Run Code Online (Sandbox Code Playgroud)
然后在AJAX网址前加上前缀config.base.
您必须将配置对象放在由PHP解析的位置; 标准选择在<head>HTML元素内.不要担心它的一个小配置对象,其内容可以在每个页面上更改,因此将其粘贴在那里是完全可靠的.
使用<base />HTML标记为所有相对URL设置URL前缀.这会影响所有相对URL:图像,链接等.
就个人而言,我会选择选项1.您很可能会发现配置对象在其他地方派上用场.