一个事件触发多个AJAX请求

时间:2016-09-19 03:06:37

标签: javascript php jquery ajax html5

    <script>
    $(document).ready(function(){
        var finishedCount = 0; //Count the amount of completed Ajax requests
         var data; //Keep track of the first request's data
         var data1; //Keep track of the second request's data
         function finished(){
             finishedCount++;
             if (finishedCount >= 2){ //2 is the amount of requests
                 //Do what you need done using data and data1
                             $(document).on('mouseenter','.grid-item',function(){
                                 var container = $(this);
                                 container.find('.title-wrap').html('<p class="job-name">'+ data +'</p>');
                                 container.find('.title-wrap').html('<p class="client-name">'+ data1 +'</p>');
                                 console.log(data);
                             });

             };
         };

            $(document).on('mouseenter','.grid-item',function(){
                 var container = $(this);
                 var jobId = container.children().find('.title-wrap-hidden').text();

         $.ajax({
             url: 'db_job_name_lookup.php',
             type: 'POST',
             data: {jobId: jobId},
             success: function(data) {
                 // success
                 data = data;
                 finished();
                                //  console.log(data);
             },
             error: function(jqXHR, textStatus, errorThrown){
                 // error
                 alert(errorThrown);
             }
         });


          $.ajax({
             url: 'db_client_name_lookup.php',
             type: 'POST',
             data: {jobId: jobId},
             success: function(data1) {
                 // success
                 data1 = data1;
                 finished();
                                //  console.log(data1);
             },
             error: function(jqXHR, textStatus, errorThrown){
                 // error
                 alert(errorThrown);
             }
         });
         });



                $(document).on('mouseleave', '.grid-item', function(){

              var container = $(this);
              container.find('.title-wrap').html('<p class="job-name"></p>');
              container.find('.title-wrap').html('<p class="client-name"></p>');

        });
    });




    </script>

大家好,我想使用一个事件来发出多个AJAX请求,我希望两个响应结果可以同时使用。我尝试使用上面的代码,但它一次只返回一个响应,它甚至看起来很混淆它应该给出的结果,我尝试使用$ .when和$ .then但我很确定我不是正确使用它。我将如何完成这项任务?

第1页

    <?php
require_once("../includes/site_init.php");


if(isset($_POST['jobId']) && $_POST['jobId'] !==NULL && $_POST['jobId'] !==0){
  $job_id = $_POST['jobId'];

  $portfolio_item_client = JobClient::find_by_sql('SELECT client_id FROM '.'job_client'." WHERE job_id = '" . $job_id . "' ");
  $client_name = Client::find_by_sql('SELECT name FROM '.'client'." WHERE id = '" .$portfolio_item_client[0]->client_id."'");
  echo $client_name[0]->name;
}else {
  echo 'result failed';
}
?>

第2页

    <?php
require_once("../includes/site_init.php");


if(isset($_POST['jobId']) && $_POST['jobId'] !==NULL && $_POST['jobId'] !==0){
  $job_id = $_POST['jobId'];

  $portfolio_item_name = Job::find_by_sql('SELECT name FROM '.'job'." WHERE id = '" . $job_id . "' LIMIT 1");
  echo $portfolio_item_name[0]->name;
}else {
  echo 'result failed';
}
?>

2 个答案:

答案 0 :(得分:2)

让我们做个比喻。 Ajax请求就像是将某人发送到商店,当他们回来时,他们会做你告诉他们的事情。你要做的是分别派两个人到商店,并强迫他们两个同时返回。那不行。

你可以做的是跟踪哪些已经返回,每当有人回来时,检查他们是否都回来了。如果是,那么你可以告诉他们一次做什么(调用一个函数)。或者,您可以有一个去商店,当他们返回时,他们可以告诉另一个人去商店,当第二个人返回时,然后告诉他们该做什么(调用一个函数)。

底线:你不能强迫他们同时完成,但你可以等到他们都完成了container.find('....

编辑:假设你需要的是在完成两个请求后执行代码,我会这样做:

    var finishedCount = 0; //Count the amount of completed Ajax requests
    var data; //Keep track of the first request's data
    var data1; //Keep track of the second request's data
    function finished(){
        finishedCount++;
        if (finishedCount >= 2){ //2 is the amount of requests
            //Do what you need done using data and data1
        }
    }
    $.ajax({
        url: 'db_job_name_lookup.php',
        type: 'POST',
        data: {jobId: jobId},
        success: function(data) {
            data = data;
            finished();
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(errorThrown);
        }
    });

    $.ajax({
        url: 'db_client_name_lookup.php',
        type: 'POST',
        data: {jobId: jobId},
        success: function(data1) {
            data1 = data1;
            finished();
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(errorThrown);
        }
    });

答案 1 :(得分:2)

尝试使用$.when来解决承诺

 $(document).on('mouseenter', '.grid-item', function() {
 var container = $(this);
 var jobId = container.children().find('.title-wrap-hidden').text();

 var ajax = $.ajax({
   url: 'db_job_name_lookup.php',
   type: 'POST',
   data: {
     jobId: jobId
   },
   success: function(data) {
     // success
     data = data;
   },
   error: function(jqXHR, textStatus, errorThrown) {
     // error
     alert(errorThrown);
   }
 });


 var ajax1 = $.ajax({
   url: 'db_client_name_lookup.php',
   type: 'POST',
   data: {
     jobId: jobId
   },
   success: function(data1) {
     // success
     data1 = data1;
   },
   error: function(jqXHR, textStatus, errorThrown) {
     // error
     alert(errorThrown);
   }
 });

 var container = $(this);
 $.when(ajax, ajax1).done(function(data, data1) {
   container.find('.title-wrap').html('<p class="job-name">'+ data +'</p>');
   container.find('.title-wrap').html('<p class="client-name">'+ data1 +'</p>');
 });


 });
 });

如果您想进行单个ajax调用,请执行以下操作:single_page.php

    <?php
require_once("../includes/site_init.php");

header('Content-Type: application/json');
if(isset($_POST['jobId']) && $_POST['jobId'] !==NULL && $_POST['jobId'] !==0){
  $job_id = $_POST['jobId'];

  $portfolio_item_client = JobClient::find_by_sql('SELECT client_id FROM '.'job_client'." WHERE job_id = '" . $job_id . "' ");
  $client_name = Client::find_by_sql('SELECT name FROM '.'client'." WHERE id = '" .$portfolio_item_client[0]->client_id."'");
  $data['client_name']=$client_name[0]->name;

  $portfolio_item_name = Job::find_by_sql('SELECT name FROM '.'job'." WHERE id = '" . $job_id . "' LIMIT 1");
  $data['portfolio_item_name']=$portfolio_item_name[0]->name;
echo json_encode(array('result'=>$data))
}else {
echo json_encode(array('result'=>'result failed'))
}
?>

JS:

 $(document).on('mouseenter', '.grid-item', function() {
     var container = $(this);
$.ajax({
       url: 'single_page.php',
       type: 'POST',
       data: {
         jobId: jobId
       },
       success: function(data) {
         container.find('.title-wrap').html('<p class="job-name">'+ data.result.portfolio_item_name  +'</p>');
       container.find('.title-wrap').html('<p class="client-name">'+ data.result.client_name  +'</p>');
       },
       error: function(jqXHR, textStatus, errorThrown) {
         // error
         alert(errorThrown);
       }
     });
 });