douwei3172 2019-01-04 05:18
浏览 112

如何在AJAX jQuery中逐个获取元素?

I'm using ajax jquery in PHP to create a rating system with database data. so far I could get the result like this. enter image description here

I want this to correct as I showed using arrows. how to achieve that output?

here is the code.

fetchrate.php

<?php

//fetch.php

$connect = new PDO('mysql:host=localhost;dbname=manpower', 'root', '');

$query = "
SELECT * FROM supplier_job WHERE jobStatus='offline' order by jobID DESC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
    $rating = count_rating($row['jobID'], $connect);
    $color = '';
    $output .= '

 <ul class="list-inline" data-rating="'.$rating.'" title="Average Rating - '.$rating.'">
 ';

    for($count=1; $count<=5; $count++)
    {
        if($count <= $rating)
        {
            $color = 'color:#ffcc00;';
        }
        else
        {
            $color = 'color:#ccc;';
        }
        $output .= '<li title="'.$count.'" jobID="'.$row['jobID'].'-'.$count.'" data-index="'.$count.'"  data-job_id="'.$row['jobID'].'" data-rating="'.$rating.'" class="rating" style="cursor:pointer; '.$color.' font-size:16px;">&#9733;</li>';
    }
    $output .= '
 </ul>
 ';
}
echo $output;

function count_rating($job_id, $connect)
{
    $output = 0;
    $query = "SELECT AVG(rating) as rating FROM ratings WHERE job_id = '".$job_id."'";
    $statement = $connect->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    $total_row = $statement->rowCount();
    if($total_row > 0)
    {
        foreach($result as $row)
        {
            $output = round($row["rating"]);
        }
    }
    return $output;
}


?>

here is the file with HTML part supplier_jobs_accept.php

<?php
$servername="localhost";
$username="root";
$password="";
$databasename="manpower";

//create connection
$conn=mysqli_connect($servername,$username,$password,$databasename);

    $queryJob="SELECT * FROM supplier_job WHERE jobStatus='offline' order by jobID DESC";

    $resultJob=mysqli_query($conn,$queryJob);
    if(mysqli_num_rows($resultJob)>0){
        while($rowJob=mysqli_fetch_assoc($resultJob)){

            $locationID=$rowJob['locationID'];
            $queryLocation="SELECT * FROM location WHERE locID='$locationID'";
            $resultLocation=mysqli_query($conn,$queryLocation);

            $rowLocation=mysqli_fetch_assoc($resultLocation);
            $locationName=$rowLocation['locName'];
            $locationAddress=$rowLocation['locStreet'].", ".$rowLocation['locVillage'].", ".$rowLocation['locCity'];


            echo "
<html>
<head>
<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js\"></script>
  <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" />
  <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>
</head>

<div class='single-post d-flex flex-row'><div class='thumb'>
                    <img src='../img/img-worker/post.png' alt=''>
                    </div>
                <div class='details'>
                    <div class='title d-flex flex-row justify-content-between'>
                        <div class='titles'>
                            <a href=''><h4>".$rowJob['jobTitle']."<small> Published on ".$rowJob['jobPublished']."</small></h4></a>
                            <h6>By ".$locationName."</h6>   
                          <span id=\"job_list\"></span> 


                        </div>
                        <ul>
                            <li><a class='btn btn-primary' href='./query_boxes/supplier_jobs_accept_accept_jobs.php?jobID=".$rowJob['jobID']."'>Apply</a></li>
                        </ul>
                    </div>
                    <p >".$rowJob['jobCount']." pieces needs to do ".$rowJob['jobType'].". Every manpower member has to work at most ".$rowJob['jobPeriod']." days. 
                    <strong></strong> Job should be complete within ".$rowJob['jobPeriod']." days.</p>

                    <h5>Job Nature: ".$rowJob['jobNature']."</h5>
                    <p class='address'><span class=''></span>".$locationAddress."</p>
                    <p class='address'><span class=''></span>".$rowJob['workersJoined']." joined.</p>
                </div></div>


        </html>

        ";






        }
    }

?>
<script>
    $(document).ready(function(){

        load_supplier_jobs_accept_data();

        function load_supplier_jobs_accept_data()
        {
            $.ajax({
                url:"fetchrate.php",
                method:"POST",
                success:function(data)
                {
                    $('#job_list').html(data);
                }
            });
        }

        $(document).on('mouseenter', '.rating', function(){
            var supplier_jobs_accept = $(this).data("supplier_jobs_accept");
            var job_id = $(this).data('job_id');
            remove_background(job_id);
            for(var count = 1; count<=supplier_jobs_accept; count++)
            {
                $('#'+job_id+'-'+count).css('color', '#ffcc00');
            }
        });

        function remove_background(job_id)
        {
            for(var count = 1; count <= 5; count++)
            {
                $('#'+job_id+'-'+count).css('color', '#ccc');
            }
        }

        $(document).on('mouseleave', '.rating', function(){
            var supplier_jobs_accept = $(this).data("supplier_jobs_accept");
            var job_id = $(this).data('job_id');
            var rating = $(this).data("rating");
            remove_background(job_id);
            //alert(rating);
            for(var count = 1; count<=rating; count++)
            {
                $('#'+job_id+'-'+count).css('color', '#ffcc00');
            }
        });

        $(document).on('click', '.rating', function(){
            var supplier_jobs_accept = $(this).data("supplier_jobs_accept");
            var job_id = $(this).data('job_id');
            $.ajax({
                url:"insert_rating.php",
                method:"POST",
                data:{supplier_jobs_accept:supplier_jobs_accept, job_id:job_id},
                success:function(data)
                {
                    if(data == 'done')
                    {
                        load_supplier_jobs_accept_data();
                        alert("You have rate "+supplier_jobs_accept +" out of 5");
                    }
                    else
                    {
                        alert("There is some problem in System");
                    }
                }
            });

        });

    });
</script>

stars of the rating are getting from the span tag called joblist. can anyone help with this problem?

  • 写回答

2条回答 默认 最新

  • dtotwai720621 2019-01-04 05:39
    关注

    I would create an array of each rating in the PHP script instead of concatenating them all to a string. In fetchrate.php, define $output as an array instead of a string. In the foreach, define a temporary string that you will add everything to instead of $output. Then at the end of each iteration, append that temporary string to $output.

    You can then send the data as encoded JSON. Here's a quick summary of that link:

    JSON encode the output before responding with it: echo json_encode($output)

    In your AJAX body, add a data type header that's assigned to JSON:

    $.ajax({
        ...
        dataType: 'json',
        ...
    });
    

    In your callback, the data parameter should now be an array.

    Now for the spans displaying the stars, I think the easiest way with the current structure (trying to keep the structure) is to index the ids of the job_list spans: set up a counter starting at 0 that is incremented each iteration of the while loop in supplier_jobs_accept.php. Suppose it's called i, then define the span like <span id=\"job_list' + i + '\"></span> so they're indexed (job_list0, job_list1, ...). Then in the AJAX callback, run an index loop through the data and update the appropriate span's html:

    for (var i = 0; i < data.length; i++) {
        $('#job_list' + i).html(data[i]);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?