如何在js文件中硬编码codeigniter链接 [英] how not to hard-code codeigniter link in js file
问题描述
$(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文件,我不能再使用该函数。
从我的回答中获取(大部分)如何获取Javascript中的相对路径?
您有两个选项:
-
在JavaScript中构建一个包含所有环境特定设置的配置/首选项对象:
var config = {
base:<?php echo base_url();?>,
someOtherPref:4
};
,然后在AJAX网址前加上
config.base
。
您必须将配置对象放在由PHP解析的位置;标准选择在
< head>
HTML元素内。不要担心它的一个小配置对象,其内容可以在每一页上改变,所以它完全可以坚持它在那里。 -
使用
< base />
HTML标记设置所有相对网址的网址前缀。这会影响所有相对网址:图片,链接等。
去选择选项1.你很可能会发现config对象在其他地方派上用场。
i wrote the routine below to retrieve city based on selected country for my codeigniter application.
$(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');
})
});
as you can see, i hard-coded the url (http://localhost/main/index.php/city/get_data_by_country) and i know it's a bad practice but i can't help it.
is there a nice clean way to not hard-code the url? i used to use codeigniter's base_url(), but since i move the routine to a js file, i am no longer able to use the function.
Taken (mostly) from my answer on How to get relative path in Javascript?.
You've got two options:
Build a configuration/ preferences object in JavaScript which contains all your environment specific settings:
var config = { base: "<?php echo base_url(); ?>", someOtherPref: 4 };
and then prefix the AJAX url with
config.base
.You have to place the config object in a place which is parsed by PHP; the standard choice is inside the
<head>
HTML element. Don't worry its a small config object, whose contents can change on each page, so it's perfectly warrented to stick it in there.Use the
<base />
HTML tag to set the URL prefix for all relative URL's. This affects all relative URL's: image's, links etc.
Personally, I'd go for option 1. You'll most likely find that config object coming in handy elsewhere.
这篇关于如何在js文件中硬编码codeigniter链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!