douxuzui4590 2014-08-23 13:41
浏览 42
已采纳

两个ajax请求在一个不存在的附加div中

I've been working on a 9gag like page. I tried to integrate a voting system which has been made by another guy, because I'm not really familiar with AJAX requests, and it just doesn't want to work.

My index.php loads five posts from the mySQL database then it appends them to the main div. After you scroll down it appends five more etc. This is done by an AJAX request which works like a charm.

When I append it to the div by AJAX, I also append some variables in the div so I can then use it for another AJAX request and this is where the problem occurs. It just doesn't do any AJAX requests. After an hour of debugging I've come to question whether one can append some data to a div, which doesn't exist in the original index.php and then run AJAX requests with it.

I won't post the pagination.js and it's stuff here because it works, I'm only going to post the ajax.php request where it could go wrong:

    <?php
    include 'config/connection.php';
    $db = "test";
    $table = "posts";

    $offset = is_numeric($_POST['offset']) ? $_POST['offset'] : die();
    $postnumbers = is_numeric($_POST['number']) ? $_POST['number'] : die();

    $run = mysqli_query($con,"SELECT * FROM $db.$table ORDER BY id DESC LIMIT ".$postnumbers." OFFSET ".$offset);

    while($row = mysqli_fetch_array($run)) {
    echo "      <article>
";
    echo "          <div id='title'><h1>".utf8_encode($row['title'])."</h1></div>
";
    echo "          <div id='image'><img src='posts/".$row['dDate']."/".$row['image']."'></div>
";
    echo "          <div id='text' class='item' data-postid='".$row['id']."' data-score='".$row['vote']."'>
";
    echo "              <p>Beküldte: ".$row['postedBy']."
";
    echo "              <div class='vote-span'><!-- voting-->
";
    echo "                  <div class='vote' data-action='up' title='Vote up'>
";
    echo "                      <i class='icon-chevron-up'></i>
";
    echo "                  </div><!--vote up-->
";
    echo "                  <div class='vote-score'>".$row['vote']."</div>
";
    echo "                  <div class='vote' data-action='down' title='Vote down'>
";
    echo "                      <i class='icon-chevron-down'></i>
";
    echo "                  </div><!--vote down-->
";
    echo "              </div>
";
    echo "          </div>
";
    echo "      </article>
";
    }
    ?>

The output looks like this:

    <article>
        <div id='title'><h1>Azért azt mondtam már hogy héjhó halihó, de igazából yolo, mert nem is igaz az, hogy ez tök gáz lenne.</h1></div>
        <div id='image'><img src='posts/2014-08-23/Screen Shot 2014-06-29 at 1.00.45 PM.png'></div>
        <div id='text' class='item' data-postid='52' data-score='0'>
            <p>Beküldte: zsombor
            <div class='vote-span'><!-- voting-->
                <div class='vote' data-action='up' title='Vote up'>
                    <i class='icon-chevron-up'></i>
                </div><!--vote up-->
                <div class='vote-score'>0</div>
                <div class='vote' data-action='down' title='Vote down'>
                    <i class='icon-chevron-down'></i>
                </div><!--vote down-->
            </div>
        </div>
    </article>

But, when I inspect the resource it's not in index.php (of course) but only in an ajax.php file, which is appended to the index.php.

Here is the votingsys.js file:

$(document).ready(function(){
// ajax setup
$.ajaxSetup({
    url: '../vote.php',
    type: 'POST',
    cache: 'false'
});

// any voting button (up/down) clicked event
$('.vote').click(function(){
    var self = $(this); // cache $this
    var action = self.data('action'); // grab action data up/down 
    var parent = self.parent().parent(); // grab grand parent .item
    var postid = parent.data('postid'); // grab post id from data-postid
    var score = parent.data('score'); // grab score form data-score

    // only works where is no disabled class
    if (!parent.hasClass('.disabled')) {
        // vote up action
        if (action == 'up') {
            // increase vote score and color to orange
            parent.find('.vote-score').html(++score).css({'color':'orange'});
            // change vote up button color to orange
            self.css({'color':'orange'});
            // send ajax request with post id & action
            $.ajax({data: {'postid' : postid, 'action' : 'up'}});
        }
        // voting down action
        else if (action == 'down'){
            // decrease vote score and color to red
            parent.find('.vote-score').html(--score).css({'color':'red'});
            // change vote up button color to red
            self.css({'color':'red'});
            // send ajax request
            $.ajax({data: {'postid' : postid, 'action' : 'down'}});
        };
        // add disabled class with .item
        parent.addClass('.disabled');
    };
});
});

aaaand the vote.php file:

    include('config/connection.php');
    # start new session
    session_start();

if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
if (isset($_POST['postid']) AND isset($_POST['action'])) {
    $postId = (int) mysql_real_escape_string($_POST['postid']);
    # check if already voted, if found voted then return
    if (isset($_SESSION['vote'][$postId])) return;
    # connect mysql db
    dbConnect();

    # query into db table to know current voting score 
    $query = mysql_query("
        SELECT vote
        from posts
        WHERE id = '{$postId}' 
        LIMIT 1" );

    # increase or dicrease voting score
    if ($data = mysql_fetch_array($query)) {
        if ($_POST['action'] === 'up'){
            $vote = ++$data['vote'];
        } else {
            $vote = --$data['vote'];
        }
        # update new voting score
        mysql_query("
            UPDATE posts
            SET vote = '{$vote}'
            WHERE id = '{$postId}' ");

        # set session with post id as true
        $_SESSION['vote'][$postId] = true;
        # close db connection
        dbConnect(false);
    }
}
}
?>

So is it possible to use another AJAX request like this or am I doing something really wrong?

I'm using jQuery 1.4.3.

  • 写回答

1条回答 默认 最新

  • dtdr84101 2014-08-23 14:13
    关注

    Aha, I bet I know what the problem is. You have five initial divs, which have click event handlers attached to them via this:

    $('.vote').click(function(){ ... });
    

    However, you are adding new divs via an infinite scroll device, and these do not have events attached to them. That is correct behaviour, since you are not re-running the code to attach them again.

    There is a clever device in jQuery that will help you get around this. It lets you attach events to things now and in the future. To use it, try this:

    $('container-selector').on('click', '.vote', function() { ... });
    

    The on method with a 'click' parameter is just the new preferred way of attaching events in jQuery, and if you add your handler as a second parameter it will just do the same as now. However if you add the new parameter, '.vote', it will attach the event to anything matching this inside the overall container selector, even if it did not exist at the time of attaching the event.

    You can use 'body' for the container selector here, but for performance reasons it is a good idea to be more specific than that. Just use whatever CSS selector will contain all of the divs to which you wish to attach this particular event handler.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化