【问题标题】:how to use two $.post methods very well for give data from 2 different database如何很好地使用两个 $.post 方法来提供来自 2 个不同数据库的数据
【发布时间】:2013-12-21 06:30:52
【问题描述】:
 function ChangeGallery(){
    var GalleryName = $('.SubSubGalleryLock').text();

    /*Send string to Data1.php and include Tags from Database*/
    $.post("Data1.php", {  Sections: GalleryName  },
    function(data){
         $(".IncludeData").append(data);
    }); 

    /*send string to Data2.php and include Events data from Database*/
    $.post("Data2.php",{  GallerySec: GalleryName  },
    function(response){
         /*when i use alert method, this function works very well, why?*/
         alert('SomeString');
     var data = jQuery.parseJSON(response);
         var ImageID  = data[0];
         var ImageSrc = data[1];
     $(ImageID).click(function(){
        $(".LargeImage").attr('src', ImageSrc);
     });
     });
};

在Data1.php中

  /*give data from database1 and print to HTML File*/
  if ($_POST['Sections']) == "String")
  {  $results = mysql_query("SELECT * FROM Table1");
  while($row = mysql_fetch_array($results))
  { echo $row['Tags']; }

在Data2.php中

  /*give data from database2 and Use for events*/
  if ($_POST['GallerySec']) == "String")
  {  $results = mysql_query("SELECT * FROM Table2");
  while($row = mysql_fetch_array($results))
  { echo json_encode($row); }

当我在客户端使用它时,Data1.php 工作得很好,但 Data2.php 仅在我编写时使用

alert('Some stringh');

之后

var data = jQuery.parseJSON(response); 

行,它工作得很好,为什么?这是什么原因造成的?

【问题讨论】:

  • 你想在ImageID 被点击后更改图片来源?
  • 它确实有效,但是当我使用 alert() 方法时
  • Works 意味着如果有警报语句,图像源已更改?
  • 当我使用警报语句时,函数(响应)很好地从数据库中提供数据,但是当我不使用它时,它不起作用

标签: php jquery


【解决方案1】:

我猜你需要在第一个.post() 之后处理第二个.post(),当你把alert() 放入时,这保证它会按那个顺序进行,但没有@ 987654324@,这是一个竞争条件,取决于哪个.post() 返回更快。

有几种方法可以解决排序问题。最直接的方法是从第一个的成功处理程序开始第二个.post(),这样您就知道第一个已经完成了。

您也可以使用 jQuery 承诺,或者您可以使用自己的标志来跟踪哪些已完成,并仅在两者都完成时调用最后一段代码。

以下是您如何从第一个的成功处理程序开始第二个.post() 以保证顺序:

function ChangeGallery(){
    var GalleryName = $('.SubSubGalleryLock').text();

    /*Send string to Data1.php and include Tags from Database*/
    $.post("Data1.php", {  Sections: GalleryName  },
    function(data){
         $(".IncludeData").append(data);
        /*send string to Data2.php and include Events data from Database*/
        $.post("Data2.php",{  GallerySec: GalleryName  },
            function(response){
                var data = jQuery.parseJSON(response);
                var ImageID  = data[0];
                var ImageSrc = data[1];
                $(ImageID).click(function(){
                    $(".LargeImage").attr('src', ImageSrc);
                });
         }); 
     });
};

【讨论】:

  • 之后的意思是我创建了一个单独的函数供第二个 .post() 使用?
  • jQuery 承诺了什么?
  • @MojtabaSh - jQuery 承诺在 jQuery 文档中有完整描述。
  • @MojtabaSh - 请参阅我添加到答案中的代码,了解如何将第二个 .post() 排序为在第一个之后。
  • 非常感谢@friend00 - 这是纠正该错误的好方法
猜你喜欢
  • 1970-01-01
  • 2014-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多