连接 Ajax 和 PHP 不起作用


connecting ajax and php not work

这段代码有什么问题?这是 Ajax 的菜单和页面更改,无需刷新页面,但它不起作用这是我的阿贾克斯代码

<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>

这是我的 HTML 标签

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

和 PHP 代码

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>
            ";
        }
    }

从数据库读取但不返回到 HTML 文件的信息。

问题出在你的 JavaScript 上。您正在等待文档准备就绪,并且(错误地)绑定了未使用的点击事件侦听器!尝试:

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

使用 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>

更好的解决方案是将 HTML 与 JavaScript 分开 - 从菜单链接中删除 onclick 属性,并使用纯 jQuery 选择它并绑定一个在单击时调用 give() 的事件:

$(document).ready(function() {
    $('.news').click(function(e) {
        give('news');
    });
});

FTFY

<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,
                        //I believe your mistake was here
                        success: function(data){
                                $('#main-unit').html(data);
                         }
                    });
            });
        });
    </script>