使用Ajax与PHP包括装货内容 [英] Loading Content using Ajax with PHP Include

查看:83
本文介绍了使用Ajax与PHP包括装货内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP网页,其中有一个div,在div有一个PHP包括含有该文件:

I have a PHP page which has a div, the div has a PHP includes which includes this file:

<?php   
    include('mySql.php');
    include('Classes.php');

    $targetPage = "blogOutput.php";
    $noOfPosts = getNumberOfPosts();
    $adjacents = 3;
?>
<link rel="stylesheet" type="text/css" href="Styles/Miniblog.css" />
<script src="Scripts/jQuery.js"></script>
<script type="text/javascript">
    var page = 1;
    $(".Button").click(onClick());
    $(document).ready(onClick());

    function onClick() {
        alert('called');
        $("#posts").load("miniBlog.php", function(response, status, xhr) {
            if (status == "error") {
                var msg = "Error!: ";
                alert(msg);
            }
        });
        page++;
    }

</script>
<div class="PostTitle">
    <h2>What's New!?</h2>
</div>
<div id="posts">
</div>
<a class="BlogButton" href="">Next</a>

我需要在不刷新页面,并重新在JavaScript中的页面变量被调用的函数的onclick。到目前为止,我已经能够做的就是让它运行脚本一次。我认为这是错误的也一样,因为它不加载任何内容。这里的页面:

I need the function "onclick" to be called without refreshing the page and resetting the "page" variable in javascript. So far, all I've been able to do is make it run the script once. I think that's wrong too, because it's not loading any content. Here's the page:

<?php
    echo "I'm here!";
    if (isset($_POST['offset'])) {
        $offset = $_POST['offset'];

        $posts = getPosts($offset);
    }
?>

<div class="BlogPost">
    <h3><?php echo $posts[0]->Title; ?></h3>
    <p><?php echo $posts[0]->Body; ?></p>
    <p class="Date"><?php echo $posts[0]->Date; ?></p>
</div>
<div id="divider"></div>
<div class="BlogPost">
    <h3><?php echo $posts[1]->Title; ?></h3>
    <p><?php echo $posts[1]->Body; ?></p>
    <p class="Date"><?php echo $posts[1]->Date; ?></p>
</div>

因此​​,要澄清:我不知道为什么我的ajax调用不工作,我不知道如何加载只在div的内容,而不是刷新整个页面。谢谢!

So, to clarify: I'm not sure why my ajax call isn't working, and I don't know how to load just the div content and not refresh the entire page. Thanks!

推荐答案

您无法看到AJAX加载,因为页面是只要你点击锚点重装内容。通过使用 preventDefault()禁用锚事件,这应该修复它。

You are not able to see content loaded by AJAX because the page is reloading as soon as you click the anchor. Disable the anchor event by using preventDefault() and this should fix it.

<script type="text/javascript">
    var page = 1;
    $(document).on('click','.BlogButton',function(e){

        // stop page from reloading
        e.preventDefault();

        $("#posts").load("miniBlog.php", function(response, status, xhr) {
            if (status == "error") {
                var msg = "Error!: ";
                alert(msg);
            }
        });
        page++;
    });
</script>

这篇关于使用Ajax与PHP包括装货内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆