在CodeIgniter中复制外部JS文件中的base_url

时间:2015-05-28 14:59:28

标签: javascript php jquery html codeigniter

我的外部js文件中有一个按钮,点击后,我想发送到我拥有的控制器。当我在JQuery中使用on click函数并将url设置为我的localhost时,它工作正常,但是我如何设置它以使其类似于base_url在CodeIgniter中的工作方式,以便它可以在任何环境中工作?我已经尝试过使用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');
});

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以在视图中将base_url值定义为JS变量,并在其下面包含所有外部JS

在这里,我给出的示例head.php部分位于/ your_root / application / views

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

答案 1 :(得分:1)

您可以将该工作留给浏览器。如果页面位于同一个域中,您不需要将其详细地放在代码上,那么可以使用类似的内容:

'"data-url="/oda/sample/instructions/' + task_id + '/' + lang + '/' + type + '"'

请注意,开头的/表示它总是会到达同一个地方,忽略当前的网址。

但是,如果您因某些原因需要编写完整网址window.location.origin,则不会包含网址的端口部分,您也必须包含window.location.port以使其适用于您的环境。并且它不是生产中必不可少的东西。 如果您在字符串上放置window.location.hosthttp:///应该有效:

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