使用外部JS文件时,Codeigniter ajax请求不起作用

时间:2016-03-19 05:26:53

标签: javascript jquery codeigniter

我的Codeigniter ajax请求在内嵌JS时有效。但是当我想将它用作外部JS文件时。它不起作用。这是为什么?

查看sample_ajax

<html>
    <head>
        <title></title>
         <script src='<?= base_url() ?>public/js/jquery.min.js'></script>
         <!--<script src='<?= base_url() ?>public/js/script.js'></script>When put script part on external script.js, it's not working -->       
    </head>
    <body>
         <div>
            <input name="submit1" id="submit1" type="button" value="Load">
        </div>
        <div id="receive" style="height: 50px; background-color: yellowgreen">       
        </div>

        <script type="text/javascript">
        $(document).ready(function () {
            $('#submit1').click(function () {
                $.ajax({
                    url: '<?php echo base_url();?>' + 'main/testarray',
                    dataType: "JSON",
                    type: "POST",
                    success: function (retdata) {
                        $("#receive").html(retdata.name);
                    }
                });
            });
        });
        </script>        
    </body> 
</html>

主控制器

class Main extends CI_Controller {
    public function test() { 
        $this->load->view('home/sample_ajax'); 
    } 
    public function testarray() {
        $student_data = [
            'name' => 'Sample Name',
            'age' => '26'
        ];
        echo(json_encode($student_data));
    }
}

2 个答案:

答案 0 :(得分:1)

首先你不需要()在echo(json_encode($ student_data));

第二,你不能复制

  

url:&#39; php echo base_url();&#39; +&#39; main / testarray&#39;

到外部js,你必须在添加外部

之前传递base_url()
<script type="text/javascript">
var base = "<?php echo base_url();?>";
</script>
<script src="<?php echo base_url();?>js/yourjavascriptexternal.js"></script>

它看起来像url:base +&#39; main / testarray&#39;

答案 1 :(得分:1)

你可以在你的标题中的javascript中创建基本url gloabl变量,或者总是加载放置此代码的视图

   <script type="text/javascript">
    var baseURL= "<?php echo base_url();?>";
    </script>

和url外部js文件路径使用此类型

<script type="text/javascript">
        $(document).ready(function () {
            $('#submit1').click(function () {
                $.ajax({
                    url: baseURL+'main/testarray',
                    dataType: "JSON",
                    type: "POST",
                    success: function (retdata) {
                        $("#receive").html(retdata.name);
                    }
                });
            });
        });
        </script>