连接ajax和php无法正常工作

时间:2013-09-11 17:49:01

标签: php jquery ajax

这段代码有什么问题? 它是菜单和页面更改由ajax刷新页面,但它无法正常工作 这是我的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>
            ";
        }
    }

从DB读取的信息但不返回html文件。

2 个答案:

答案 0 :(得分:1)

问题在于你的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');
    });
});

答案 1 :(得分:0)

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>