doudi2229 2013-09-11 17:49
浏览 22
已采纳

连接ajax和php无法正常工作

what is the problem of this code? it is menu and page change by ajax with out refreshing the page, but its not working it is my ajax code

<script>
        $(document).ready(function() {
            $('.news').click(function give(id){
                $('#main-unit').text('Please Wait...');
                    var place= id;
                    $.ajax({
                        url:'pages/news.php',
                        type:'POST',
                        data:'where='+place,
                        statusCode:{
                            success: function(data){
                                $('#main-unit').html(data);
                            }
                        }
                    });
            });
        });
    </script>

this is my html tags

<ul>
   <li><a class="news" onclick=\"give('news')\" href="#">news</a></li>
</ul>

and php code

mysql_connect("localhost", "root", "")
    or die(mysql_error()); 
    mysql_select_db("basi")
    or die(mysql_error()); 
    if($_POST['where']=='news'){
        $result = mysql_query("SELECT * FROM contents WHERE type = 0");
        while ($row = mysql_fetch_array($result)){
            $title = $row['title'];
            $text = $row['text'];
            echo"
            <div class='title'><span>$title</span></div>
            <div class='content'>
            $text
            </div>
            ";
        }
    }

the information read from DB but dont return to html file.

  • 写回答

2条回答 默认 最新

  • douliang1369 2013-09-11 18:12
    关注

    The problem is with your JavaScript. You're waiting for document ready and (incorrectly) binding a click event listener that isn't being used! Try:

    <a class="news" onclick="give('news')" href="#">news</a>
    

    with the JavaScript:

    <script>
        function give(id) {
            $('#main-unit').text('Please Wait...');
            var place = id;
            $.ajax({
                url:'pages/news.php',
                type:'POST',
                data:'where='+place,
                statusCode:{
                    success: function(data){
                        $('#main-unit').html(data);
                    }
                }
            });
        }
    </script>
    

    A better solution would be to separate HTML from JavaScript - remove the onclick attribute from your menu link, and use pure jQuery to select it and bind an event that calls give() when it is clicked:

    $(document).ready(function() {
        $('.news').click(function(e) {
            give('news');
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序