如何不在js文件中硬编码codeigniter链接

how not to hard-code codeigniter link in js file

本文关键字:编码 codeigniter 链接 文件 何不 js      更新时间:2023-09-26

我为我的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');
    })
});

如你所见,我硬编码的url (http://localhost/main/index.php/city/get_data_by_country),我知道这是一个不好的做法,但我忍不住。

是否有一种干净的方法来不硬编码url?我曾经使用codeigniter的base_url(),但由于我将例程移动到js文件中,我不再能够使用该函数。

(大部分)取自我关于如何在Javascript中获得相对路径的回答

你有两个选择:

  1. 在JavaScript中构建一个包含所有环境特定设置的配置/首选项对象:

     var config = {
         base: "<?php echo base_url(); ?>",
         someOtherPref: 4
     };
    

    ,然后用config.base作为AJAX url的前缀。

    你必须把配置对象放在PHP解析的地方;标准的选择是在<head> HTML元素中。不要担心它是一个小的配置对象,它的内容可以在每个页面上改变,所以把它放在那里是完全合理的。

  2. 使用<base /> HTML标签设置所有相对URL的URL前缀。这影响所有相对URL:图像,链接等。

就我个人而言,我会选择选项1。您很可能会发现该配置对象在其他地方会派上用场。

"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

您可以做的一件事是为页面上的元素添加data-baseurl属性(body元素有效)。然后你可以从JavaScript文件中获取。

<body data-baseurl="<?=base_url()?>">

然后在JavaScript中:

$("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');
})