如何在AJAX jQuery中一一获取元素?

时间:2019-01-04 05:18:59

标签: javascript php jquery html ajax

我正在PHP中使用ajax jQuery创建具有数据库数据的评估系统。到目前为止,我可以获得这样的结果。 enter image description here

我希望此问题能够像使用箭头所示进行纠正。如何实现该输出?

这是代码。

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;
}


?>

这是带有HTML部分的文件 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>
评级的

颗星来自称为工作清单的span标签。有人可以帮助解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

我将在PHP脚本中创建每个等级的数组,而不是将它们全部串联为一个字符串。在fetchrate.php中,将$output定义为数组而不是字符串。在foreach中,定义一个临时字符串,您将向其中添加所有内容,而不是$output。然后在每次迭代结束时,将该临时字符串附加到$output

然后您可以send the data as encoded JSON。这是该链接的快速摘要:

JSON对输出进行编码,然后再对其进行响应:echo json_encode($output)

在AJAX正文中,添加分配给JSON的数据类型标头:

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

在您的回调中,data参数现在应该是一个数组。

现在对于显示星星的跨度,我认为使用当前结构的最简单方法(尝试保持结构)是索引job_list跨度的ID:设置一个从0开始的计数器,即使whilesupplier_jobs_accept.php循环的每次迭代递增。假设它称为i,然后像<span id=\"job_list' + i + '\"></span>那样定义范围,以便对其进行索引(job_list0job_list1,...)。然后在AJAX回调中,对数据运行索引循环并更新相应跨度的html:

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

答案 1 :(得分:0)

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 class=\"job-list-\"".$rowJob['jobID']."></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)
                {
                    //json data from php
                    result = JSON.parse(data);
                    $.each(data, function(i, item) {                        
                        $('.job-list-'+item.id).html(item.output);
                    });

                }
            });
        }

        $(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>      

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 = '';
// add array to handle html data
$jobs = array();
foreach($result as $row)
{
    $i= 0;
    $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>
 ';
 $jobs[$i]['id'] = $row['jobID'];
 $jobs[$i]['output'] = $output;
 $i++;
}
//use json for sending data ajax
echo json_encode($jobs);


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;
}


?>