Javascript 如何不在js文件中硬编码codeigniter链接
我编写了下面的例程,根据我的codeigniter应用程序选择的国家检索城市Javascript 如何不在js文件中硬编码codeigniter链接,javascript,jquery,codeigniter,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() },
$(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');
})
});
如您所见,我硬编码了url(http://localhost/main/index.php/city/get_data_by_country)我知道这是一种不好的做法,但我无法控制
有没有一种干净的方法可以让url不被硬编码?我以前使用codeigniter的base_url(),但由于我将例程移动到js文件,我不再能够使用该函数。更改”http://localhost/main/index.php/city/get_data_by_country“
到”/main/index.php/city/get_data_by_country“
,无论您的基本url是什么,它都会工作
这是因为main/index.php
之前的/
说明“从根目录开始,然后转到main
文件夹中的index.php
文件”
除非您的文档根文件夹设置为main
文件夹,否则,请从我的答案中取出main
。
您有两个选择:
var config = {
base: "<?php echo base_url(); ?>",
someOtherPref: 4
};
var配置={
基:“,
其他人:4
};
然后在AJAX url前面加上config.base
您必须将config对象放置在PHP解析的位置;标准选项在
HTML元素中。别担心,它是一个很小的配置对象,每个页面上的内容都可以更改,所以最好将它放在那里就个人而言,我会选择选项1。您很可能会发现配置对象在别处派上了用场。您可以做的一件事是向页面上的元素添加一个
databaseurl
属性(body元素起作用)。然后您可以从JavaScript文件中获取它
<body data-baseurl="<?=base_url()?>">
不会
/index.php
链接到http://localhost/index.php
,而不是http://localhost/main/index.php
?是的,它将丢失主文件夹部分。更新。我忘了回来选择你的答案。我选择了选项2,因为我认为base_url()在.js文件上不起作用。谢谢。选项1更好,它不是js文件,而是PHP文件。
$("select#cbo_country").change(function() {
var baseURL = $('body').data('baseurl')
$.post(baseURL+"city/get_data_by_country", {
int_country_id : $(this).val()
},
function(data) {
// some code here
},'json');
})