dongquan8753 2013-12-15 10:11
浏览 23
已采纳

jQuery GET正在为我做准备。 使用CodeIgniter。 它返回视图的源代码而不是一个值

I am trying to test the jQuery GET method, but what I am getting as result is completely insane. All I am trying to do is call a function from my controller with jQuery and then display the echoed value in a div within my view. Below is my code and finally a breakdown of the problem I am encountering.

Controller

public function generate_suggestions2() {

        echo "James";   
}

View views\suggestions_v.php

<body>
//This DIV is used a button to call the jQuery function
<div id="next_btn">
   <p>Click here to display a name</p>         
</div> 

//In this div the value retrieved by the jQuery should be displayed
<div id="listB"></div>

//This is the function that calls the function within my controller
<script type="text/javascript">

    $( "#next_btn" ).click(function() {

        $.get("core/generate_suggestions2/",
        function(data) {

            $( "#listB" ).html(data);
        });
    });
</script> //For some reason I need to put the script at the end of the body. When it's in the head nothing happens when I click the button. Also something I do not understand.

</body>

Now the problem is that when I click the DIV next_btn it does NOT display the James in the DIV listB.

Instead it populates the DIV listB with my source code from my main view views\core_v.php I have no idea how this is even remotely possible, so please if you have a clue or even better you know what I am doing wrong please tell me. I am trying to get this to work for the past three days without any success or progress :(

  • 写回答

2条回答 默认 最新

  • duanhuiqing9528 2013-12-15 10:23
    关注

    Try using this code in your view

    <script type="text/javascript">
        "$( "#next_btn" ).click(function() {
    
            $.get("<?php echo site_url().'/core/generate_suggestions2';?>",
            function(data) {
    
                $( "#listB" ).html(data);
            });
        });"
    </script>
    

    Also delete the </script> tag just right before this block comment.

    Regarding this comment you have:

    //For some reason I need to put the script at the end of the body. When it's in the head nothing happens when I click the button. Also something I do not understand.
    

    It is because the DOM is not yet fully loaded and Javascript executes its code when the browser has finished loading the DOM you are referring to. So you either have to put it after the DOM element you want to edit, like you do now or you could use $(document).ready(function(){ } ); . Read more about it here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?