Javascript 在CodeIgniter中复制外部JS文件中的基本url

Javascript 在CodeIgniter中复制外部JS文件中的基本url,javascript,php,jquery,html,codeigniter,Javascript,Php,Jquery,Html,Codeigniter,我的外部js文件中有一个按钮,单击该按钮时,我希望被发送到我拥有的控制器。当我在JQuery中使用on-click函数并将url设置为我的本地主机时,它工作得很好,但是如何设置它,使其工作方式与CodeIgniter中的base_url工作方式类似,以便它在任何环境中都能工作?我尝试过使用window.location.origin或window.location.host而不是localhost,但两者都不起作用。有什么想法吗 我的外部JS按钮: var html = '<div cla

我的外部js文件中有一个按钮,单击该按钮时,我希望被发送到我拥有的控制器。当我在JQuery中使用on-click函数并将url设置为我的本地主机时,它工作得很好,但是如何设置它,使其工作方式与CodeIgniter中的base_url工作方式类似,以便它在任何环境中都能工作?我尝试过使用window.location.origin或window.location.host而不是localhost,但两者都不起作用。有什么想法吗

我的外部JS按钮:

var html = '<div class="alert alert-success" role="alert"><p class="instruction_text text-center">' + completedText + '</p></div><input id="next_task" class="btn btn-lg btn-default text-center" style="margin-top: 150px; font-weight: bold;" type="button" value="' + text[lang]['continue'] + '"data-url="http://localhost:8888/oda/sample/instructions/' + task_id + '/' + lang + '/' + type + '">';

$('#final_message').append(html);

$(document).on('click', '#next_task', function(e) {
    e.preventDefault();
    location.href = $(this).data('url');
});
var html='

'+completedText+”

; $('final#u message')。附加(html); $(文档)。在('单击','下一个任务')上,函数(e){ e、 预防默认值(); location.href=$(this.data('url'); });

谢谢

您可以在视图中为JS变量定义base_url值,并包括该变量下方的所有外部JS

这里,我给出了示例head.php的一节,它位于/your_root/application/views

<script>
var base_url = "<?php echo base_url(); ?>";
</script>

var base_url=“”;

您可以将该工作留给浏览器。如果页面位于同一个域中,您不需要将其详细地放在代码中,您可以这样放置:

'"data-url="/oda/sample/instructions/' + task_id + '/' + lang + '/' + type + '"'
请注意,开头的
/
表示它将始终到达相同的位置,而不考虑当前的url

但是,如果出于某种原因需要编写完整的url
window.location.origin
将不包括url的端口部分,那么您也必须包括
window.location.port
,以使其与您的环境一起工作。这不是生产中必须做的事情。 如果将
http://
/
放在字符串上,则
window.location.host
应该可以工作:

'"data-url="http://' + window.location.host + '/oda/sample/instructions/' + task_id + '/' + lang + '/' + type + '"'

您是否在application/config/config.php上为base_url定义了一个值,或者它是自动生成的?这是一个很简单的修复方法。我把它弄得太复杂了。谢谢你的帮助!