Jquery 如何使用ajax实现这一点?

Jquery 如何使用ajax实现这一点?,jquery,ajax,Jquery,Ajax,您好,有人可以向我解释一下,我如何使用ajax实现这一点,这样就没有页面刷新了。一般来说,我不熟悉使用ajax和jquery,任何帮助和解释都会很好 这是我的php代码 <div class="recentwork"> <div class="imgholderfloat"> <?php include 'process/connect.php'; $small_path = "/work/small/"; $large_path = "/work/large/";

您好,有人可以向我解释一下,我如何使用ajax实现这一点,这样就没有页面刷新了。一般来说,我不熟悉使用ajax和jquery,任何帮助和解释都会很好

这是我的php代码

<div class="recentwork">
<div class="imgholderfloat">
<?php
include 'process/connect.php';
$small_path = "/work/small/";
$large_path = "/work/large/";
$full_path  = "/work/full/";


$per_page = 3;
$pages_query = "SELECT id FROM projects";
$pages_result = mysqli_query( $link, $pages_query );
$pages = ceil(mysqli_num_rows($pages_result) / $per_page);

if ($_GET['page'] > $pages) {
    $page = 1;
} else {
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
}
$start = ($page - 1) * $per_page;



$query = " SELECT * FROM projects INNER JOIN orders ON orders.id = projects.order_id LIMIT $start, $per_page";
$result = mysqli_query( $link , $query );
$num_rows = mysqli_num_rows($result);                               

while ($row = mysqli_fetch_assoc($result)){
echo '<div class="imgholder"><a href="'.$full_path.''.
    $row['filename'].'"><img src="'.$small_path .''.$row['filename'].'" /></a><div class="largeimg"><a href="'.$full_path.''.$row['filename'].'"><img src="'.$large_path.''.$row['filename'].'" /></a></div>
<div class="details">
<p><span class="red">Theme</span>: '.$row['theme'].'</p>
<p><span class="red">Budget</span>: '.$row['budget'].'</p>
<p><span class="red">Type</span>: '.$row['type'].'</p>
<p><span class="red">Misc</span>: '.$row['misc'].'</p>
</div>
</div>
';
}
if ($pages > 1 && $page < $pages) {
    echo '<span class="morebtn" ><a href="?page='. $page= $page + 1 .'" >MORE</a></span>';
} 
else {
    echo '<span class="morebtn" ><a href="?page='. $page= $page - 1 .'" >BACK</a></span>';
}
?>

</div>
</div>

结合使用jQuery,您可以尝试以下方法:

$("a#morebutton").click(function() {
    var xhr = new XMLHttpRequest();
    var result_target=$('#imgholder');
    xhr.open("get", "index.php"+this.href, true);
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4){
            if(xhr.status >= 200 && xhr.status < 300){ 
                $(result_target).html(xhr.responseText);
            }
        }           
    };
    xhr.send(null);
});
$(“更多按钮”)。单击(函数(){
var xhr=new XMLHttpRequest();
var结果_target=$('imgholder');
open(“get”,“index.php”+this.href,true);
xhr.onreadystatechange=函数(){
if(xhr.readyState==4){
如果(xhr.status>=200&&xhr.status<300){
$(result\u target).html(xhr.responseText);
}
}           
};
xhr.send(空);
});

这完全出乎我的意料,我在自己所有的XHR调用中都使用了这种格式,可能需要一些调整才能让它按照您的意愿运行。

通过阅读您的代码,我认为这就是您想要的:

$(".morebtn a").click(function(e) {
    e.preventDefault();

    $.get("index.php"+$(this).attr("href"), function(result) {
        $(".imgholderfloat").html(result);
    });
}

我认为在Ajax中演示如何使用GET请求更改图像背后的概念更有意义。如何在代码中适应这一点是如何组织代码的问题,但是可以通过两种不同的方式来实现

下面,我将演示一种方法,用
返回一个HTML片段,以替换当前图像并处理错误、第一个/最后一个/上一个/下一个关注点等。这是为了向你展示如何在一个抽象的案例中做到这一点;最终如何使用代码将取决于您。请确保并阅读下面代码中的注释,以了解我所做的解释

要查看以下操作,请参阅:

注意:在确定代码片段之前,我不会发送所有HTML。这允许我用一个PHP脚本处理这两个请求。但是,您可以使用两种不同的脚本来执行此操作


如果你展示了你所做的尝试,你可能会得到更好的响应。我会的,我会放弃它,因为它不起作用,但基本上我使用了jquery的.ajax函数,并试图通过a tags href属性将get变量传递到索引页,Ajax中的GET调用只是一个附加了GET键/值的URL。尝试硬编码,看看会发生什么。您还应该有一种返回标记片段的方法;你不需要返回整个HTML,只需要替换页面上的内容。我再试试,然后发布我得到的内容。我没有在上面的代码中看到带有class
morebutton
的锚。这应该是
a#morebtn
?您好,这似乎正是我想要的,但是,它将整个页面重新加载到.imgholder div中。我该如何更改它,使它只重新加载该div的内容。nvm使其正常工作,我没有意识到,在ajax调用占据整个页面时,您只能得到希望返回的信息。好吧,我开始理解一些事情,直到成功为止。关于成功,我们究竟如何管理展示的内容?例如,当我传递url时,它将返回整个页面,而不仅仅是div的内容。我如何告诉ajax只替换.imgholder div的内容,而不将整个新页面放在div中。
$(".morebtn a").click(function(e) {
    e.preventDefault();

    $.get("index.php"+$(this).attr("href"), function(result) {
        $(".imgholderfloat").html(result);
    });
}
<?php 

// My ad hoc array of images. You of course will be 
// generating this list from a database call.

$images = array(
    'http://upload.wikimedia.org/wikipedia/commons/d/db/087882_cf786e35-by-Roger-May.jpg',
    'http://upload.wikimedia.org/wikipedia/commons/6/6c/173865_d45f46f7-by-dave-challender.jpg',
    'http://upload.wikimedia.org/wikipedia/commons/9/97/188798_e4bc708f-by-Stephen-McKay.jpg',
    'http://upload.wikimedia.org/wikipedia/commons/c/c0/205765_f6ccbfdb-by-Stephen-G-Taylor.jpg'
);

// I use a switch to determine full html or just a
// snippet to return. Note, it defaults to full.

switch ($_GET['type']) {
    case 'snippet': 
        $type = 'snippet';
        break;
    default:
        $type = 'full';
}

// Determine the current, first, and last ids.

$imgid = (int) $_GET['img'];
$first = 0;
$last = count($images) - 1;

// If it's not real, reset to the beginning photo.

if (!$images[$imgid]) {
    $imgid = 0;
}

// Here I determine what the previous and last img ids
// will be.

$previous = ($imgid < 1 ? $last : $imgid - 1);
$next = ($imgid >= $last+1 ? 0 : $imgid + 1);

// If I just need to return a snippet, then do that and
// exit. This prevents the full code from returning,
// and does so based on the GET `type` value provided.

if ($type == 'snippet') {
    echo "<img class='view' src='{$images[$imgid]}'/>";
    exit;
}

// This will output the full page. Note, it also
// accounts for when the Ajax produces an error, since
// it will respond correctly to a URL with no `type`
// provided and with an `img` value.

echo <<<HTML
<html>
<head>
<style type="text/css">
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){
    $('.browse').click(function(){
        that = $(this);
        // I use the `rel` attribute to store image-
        // related data. Each ANCHOR has the reference
        // to the imgid it needs to request the correct
        // image snippet.
        var imgid = that.attr('rel');
        // I need this for errors. This allows me to
        // show the image by bypassing the Ajax call when
        // it doesn't work correctly.
        var href = that.attr('href');
        $.ajax({
            // Note, `get` is default, but I provided it
            // for demonstration purposes and to make it
            // clear this is what is happening.
            type: 'get',
            // Note the `type=snippet` part.
            url: 'getimages.php?type=snippet&img='+imgid,
            // What to do when the Ajax call appears to 
            // complete successfully.
            success: function(data){
                // If the server didn't respond with an
                // `<img .../>` tag, send the browser to
                // the `href` instead. 
                if (data.indexOf('<img') == -1) {
                    window.location = href;
                }
                // I'm going to replace the image with the
                // new image I just got.
                $('.view').replaceWith(data);
                // The bits that manipulate the current
                // page's values for next and previous.
                // Note the use of the `rel` tag here.
                var first = $('#first').attr('rel');
                var last = $('#last').attr('rel');
                var previous = $('#previous').attr('rel') - 1;
                var next = $('#next').attr('rel') - 0 + 1;
                if (previous < 0) previous = last;
                if (next > last || next == last) next = 0;
                $('#previous').attr('rel', previous);
                $('#next').attr('rel', next);
            },
            // Again, if the Ajax call errors out, I simply
            // send the browser to the url found in the `href`.
            error: function(){
                window.location = href;
            }
        });
        // Cancel the browser following the `href` tag.
        return false;
    });
});

</script>
</head>
<body>
<div>
<img class="view" src="{$images[$imgid]}"/>
<p>
 <a class="browse" id="first" rel="$first" href="?img=$first">First</a>
 <a class="browse" id="previous" rel="$previous" href="?img=$previous">Previous</a>
 <a class="browse" id="next" rel="$next" href="?img=$next">Next</a>
 <a class="browse" id="last" rel="$last" href="?img=$last">Last</a>
</p>
</div>
</body>
</html>
HTML;

?>
<html>
<head>
<style type="text/css">
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){
    $('.browse').click(function(){
        that = $(this);
        // I use the `rel` attribute to store image-
        // related data. Each ANCHOR has the reference
        // to the imgid it needs to request the correct
        // image snippet.
        var imgid = that.attr('rel');
        // I need this for errors. This allows me to
        // show the image by bypassing the Ajax call when
        // it doesn't work correctly.
        var href = that.attr('href');
        $.ajax({
            // Note, `get` is default, but I provided it
            // for demonstration purposes and to make it
            // clear this is what is happening.
            type: 'get',
            // Note the `type=snippet` part.
            url: 'getimages.php?type=snippet&img='+imgid,
            // What to do when the Ajax call appears to 
            // complete successfully.
            success: function(data){
                // If the server didn't respond with an
                // `<img .../>` tag, send the browser to
                // the `href` instead. 
                if (data.indexOf('<img') == -1) {
                    window.location = href;
                }
                // I'm going to replace the image with the
                // new image I just got.
                $('.view').replaceWith(data);
                // The bits that manipulate the current
                // page's values for next and previous.
                // Note the use of the `rel` tag here.
                var first = $('#first').attr('rel');
                var last = $('#last').attr('rel');
                var previous = $('#previous').attr('rel') - 1;
                var next = $('#next').attr('rel') - 0 + 1;
                if (previous < 0) previous = last;
                if (next > last || next == last) next = 0;
                $('#previous').attr('rel', previous);
                $('#next').attr('rel', next);
            },
            // Again, if the Ajax call errors out, I simply
            // send the browser to the url found in the `href`.
            error: function(){
                window.location = href;
            }
        });
        // Cancel the browser following the `href` tag.
        return false;
    });
});

</script>
</head>
<body>
<div>
<img class="view" src="http://upload.wikimedia.org/wikipedia/commons/d/db/087882_cf786e35-by-Roger-May.jpg"/>
<p>
 <a class="browse" id="first" rel="0" href="?img=0">First</a>
 <a class="browse" id="previous" rel="3" href="?img=3">Previous</a>

 <a class="browse" id="next" rel="1" href="?img=1">Next</a>
 <a class="browse" id="last" rel="3" href="?img=3">Last</a>
</p>
</div>
</body>
</html>
<img class='view' src='http://upload.wikimedia.org/wikipedia/commons/6/6c/173865_d45f46f7-by-dave-challender.jpg'/>