how to get the base url in javascript

前端 未结 10 1848
一整个雨季
一整个雨季 2020-12-01 04:12

I am building a website with CodeIgniter, I have various resources that I load with the base_url helper function like this

10条回答
  •  情话喂你
    2020-12-01 04:32

    I may be late but for all the Future geeks. Firstly i suppose you want to call base_url in your .js file. so lets consider you are calling it on below sample .js file

    sample.js

    var str = $(this).serialize(); 
    
    jQuery.ajax({
    type: "POST",
    url: base_url + "index.php/sample_controller",
    dataType: 'json',
    data: str,
    success: function(result) {
    alert("Success");
    }
    

    In the above there is no base_url assigned.Therefore the code wont be working properly. But it is for sure that you'll be calling the .js in between or of View file by using tag. So to call base_url in.js file, we have to write the below code where you plan to call the .js file. And it is recommended that you create common header file and place the below code and all the calling style sheets (.css) and javascript (.js) file there. just like below example.

    common header file

    
    
    
    
    
    
    
    
    
    
    
    

    Now the base_url will work in sample.js file as well. Hope it helped.

提交回复
热议问题