Codeigniter基本网址在javascript中无法识别 [英] Codeigniter base url didn't recognized in javascript
问题描述
我的CI应用程序中有一个ajax请求,这是我的cstom.js文件。
I have an ajax request in my CI application ,here is my cstom.js file for that purpose.
$(document).ready(function(){
var base_url='<?php echo base_url();?>';
$('#add-ct').click(function(){
$.ajax({
url:base_url+'stockmanagement/add_category',
data:{category:$('#category').val()},
success:function(data){
alert(data);
},
error:function(err){
alert('error'+err);
}
});
});
});
但 base_url
未重新定殖,当我检查调试控制台时, base_url
的打印方式与源代码一样。
But the base_url
didn't recolonized, when i check the debug console the base_url
is printed as the same as the source code like this way.
var base_url='<?php echo base_url(); ?>';
更新
我的javascript文件包含在视图文件中
my javascript file is included in a view file
<?php if($page=='add-category'){ echo '<script src="'.base_url().'/assets/js/custom.js"></script>'; }?>
推荐答案
问题是你正在尝试运行PHP代码在JS文件中。这不起作用,因为PHP代码只能在以 .php
扩展名命名的文件中运行。
The problem is that you are trying to run PHP code inside a JS file. This will not work as PHP code can only run inside files named with a .php
extension.
要修复此问题,你必须在Javascript中设置一个全局变量来保存你的base_url的值
To fix this, you have to set a global variable in Javascript to hold the value of your base_url
所以如果你想要包含一个JS文件,你应该首先定义变量,就像在以下示例:
so if you want to include a JS file you should first define the variable like in the following example:
index.php
<html>
<head>
<!-- SET GLOBAL BASE URL -->
<script>var base_url = '<?php echo base_url() ?>';</script>
<script src="/assets/js/custom.js"></script>
</head>
<body>
</body>
</html>
custom.js
//now we can reference the base_url
alert(base_url+"some/other");
这篇关于Codeigniter基本网址在javascript中无法识别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!