how not to hard-code codeigniter link in js file

旧时模样 提交于 2019-12-22 10:25:03

问题


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.


回答1:


Taken (mostly) from my answer on How to get relative path in Javascript?.

You've got two options:

  1. 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.

  2. 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.




回答2:


Change "http://localhost/main/index.php/city/get_data_by_country" to "/main/index.php/city/get_data_by_country" and it will work no matter what your base url is.

This works because the / before main/index.php says "start at the root and go the the index.php file in the main folder".

This is unless your document root folder is set to the main folder, if so, take out the main




回答3:


One thing you can do is add a data-baseurl attribute to an element on the page (the body element works). Then you can grab that from the JavaScript file.

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

Then in 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');
})


来源:https://stackoverflow.com/questions/7415468/how-not-to-hard-code-codeigniter-link-in-js-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!