【问题标题】:Function didn't run as expected功能未按预期运行
【发布时间】:2014-08-10 18:57:14
【问题描述】:

首先我使用 jquery、php、sql、html 和 css。

我正面临一个给我带来严重问题的问题。我正在尝试运行 $.post 函数以从我的聚会组数据库中检索值(4 个成员值存储在数据库的 4 列中。检索值后,我运行一个 while 循环并将聚会的每个值附加到列表视图。

然后我将当前的 while 循环值发送到另一个 $.post 函数以检查我当前正在检查的成员的评分,并检索结果以显示在我当前附加的 li 上。

这就是我所拥有的

$('body').on("pagebeforeshow","#p-partyDetail",function(){                  
                var teamID = globalIndex;
                var currentMem = "";

                $.post("retrieveMemDetails.php", 
                {
                    teamID:teamID, // data to pass into php     
                    username:globalUsername,                
                },  // data to pass into php                                                                                    
                    function(response)
                    {
                        var x = 1; // define value as 1

                        while(x<=4){ // if loop is below or equal to 4, run loop                                                            
                            //member = response.mem + x;
                            member = response['mem' + x]; // define member1 in variable, 
                            currentMem = member;
                            console.log("current x value is " + x);

                            if(member !=""){
                                var y = x.toString();
                                console.log("y is " + y);

                                $.post("retrieveRatingDetails.php", 
                                {
                                    username:currentMem, // data to pass into php                                                                           
                                },  // data to pass into php                                                                        
                                    function(response2)
                                    {                                                                                       
                                        $("p#" +y).html(response2.rating);
                                        console.log("full name is " + response2.name + " rating is " + response2.rating);
                                        console.log("retrieve rating valued:"+response2.rating+" to p#"+y);
                                        console.log("end of loop cycle" + y);
                                    }, 'json'
                                );                                                                  

                                $("#partyDetail-listview").append('<li> <img src="images/final-fantasy-7-final-fantasy-vii-6973833-1024-768.jpg"> <h2>'+ member + '</h2> <p id="'+ x +'"></p> </li>').listview("refresh");  
                                console.log("appended count:" + x);
                            }   
                            x++;                            
                        }                               
                    }, 'json'
                );
            });

用于检索成员详细信息的我的 php

include_once('db.php');
session_start(); 

$teamID = ($_POST['teamID']);
$username = ($_POST['username']);

$result = $db->query("SELECT * FROM `studentparty` WHERE `id` = '".$teamID."'");
$result3 = $db->query("SELECT *` FROM `userdetails` WHERE `username` = '".$username."'");

    if(mysqli_num_rows($result)>0)
    {
        $row = mysqli_fetch_array($result);
        $mem1 = $row["mem1"];
        $mem2 = $row["mem2"];
        $mem3 = $row["mem3"];
        $mem4 = $row["mem4"];

        $result2 = json_encode(array("mem1"=>$mem1, "mem2"=>$mem2, "mem3"=>$mem3, "mem4"=>$mem4)); 
            echo $result2;
    }

用于检索评分的我的 php

include_once('db.php');
session_start(); 

$username = ($_POST['username']);

$result4 = $db->query("SELECT * FROM `userdetails` WHERE `username` = '".$username."'");

    if(mysqli_num_rows($result4)>0)
    {
        $row = mysqli_fetch_array($result4);
        $rating = $row["Rating"];
        $name = $row["FullName"];

        $result5 = json_encode(array("rating"=>$rating, "name"=>$name)); 
            echo $result5;      
    }

我的会员和评分在不同的表格下,所以我两次调用 $.post。

显然调试了几个小时后,我发现它会循环播放

console.log("current x value is " + x);

然后

console.log("y is " + y);

然后

console.log("appended count:" + x);

在运行前运行总循环数为 4

console.log("full name is " + response2.name + " rating is " + response2.rating);
console.log("retrieve rating valued:"+response2.rating+" to p#"+y);
console.log("end of loop cycle" + y);

这导致评分只在值 y 上不断更新,因为函数的流程已经错误。

我的理想流程是 - 从 php 中检索党员详细信息 -当使用while循环从php显示mem1时,只附加一个li我的ul。 - 将当前 mem1 数据发送到我的下一个 $.post 函数以检索评级数据 - 使用评级数据更新 li - 循环结束并从 member2 开始

有人可以指出我的脚本有什么问题吗?谢谢!

【问题讨论】:

  • 为什么不获取详细的评分信息?通过加入他们,您不必进行第二次发布请求,这意味着您不必等待队列(异步回调),也不必如此努力地推动您的数据库获得 4 次而不是一次的评分。跨度>
  • 因为它们在不同的表下,所以我有一个党员表,还有一个 userDetail 表,评分在这个 userDetail 表中。我可以将评分值复制并粘贴到党员通过添加 mem1Rating mem2Rating.. 等表,但我认为这就像玩作弊一样,因为评级更适合 userDetail
  • 你知道为什么它会跳过我的第二个 $.post 请求并继续循环直到它循环完成然后运行我的第二个 $.post 请求吗?
  • 因为 jquery 中的回调函数是异步的,这意味着你必须等到 parent 的闭包结束。因此,您将能够在 while 循环结束后使用response2。您可以将回调函数设置为同步,但您需要使用 $.ajax() 并使用 async: false

标签: javascript php jquery html sql


【解决方案1】:

我强烈建议一个 ajax 请求足以获取请求的数据。如果您发出内部 ajax 请求,则必须等待其他行执行。因为它是异步函数。您还可以使用以下代码同步设置您的 ajax 调用:

$.ajax({
  ...
  async: false,
  ...
});

但是你必须等到你的回调函数被执行。所以,有时这对你的表现很危险。

如果你像下面这样改变你的 php 端,你会得到一个包含有成员和成员详细信息的对象的数组。

include_once('db.php');
session_start(); 

$teamID = ($_POST['teamID']);

$result_detail = $db->query("SELECT * FROM `studentparty` WHERE `id` = '".$teamID."'");

if(mysqli_num_rows($result_detail) > 0)
{
  $data = array();
  $mem = array();

  $row = mysqli_fetch_array($result);
  $mem[0] = $row["mem1"];
  $mem[1] = $row["mem2"];
  $mem[2] = $row["mem3"];
  $mem[3] = $row["mem4"];

  for($i = 0; $i < count($mem); $i++) {
    $result_rating = $db->query("SELECT *` FROM `userdetails` WHERE `username` = '".$mem[$i]."'");
    $rating_array = array();

    if(mysqli_num_rows($result_rating) > 0)
    {
      $row2 = mysqli_fetch_array($result_rating);
      $rating = $row2["Rating"];
      $name = $row2["FullName"];

      $rating_array = array("rating"=>$rating, "name"=>$name)); 
    }

    $data[$i] = array_merge(array("member" => $mem[$i]), $rating_array);
  }

  $result_json = json_encode($data); 
  echo $result_json;
}

我还采用了您的 javascript 代码来响应新的响应。我无法测试两者。我希望它会运作良好。

$('body').on("pagebeforeshow","#p-partyDetail",function(){                  
  var 
  teamID = globalIndex,
  currentMem = "",
  callback = function(response) {
    var member, id;
    $.each(response, funciton(i, obj) {
      member = obj['member'];
      id = (i+1); // if you have ids for members, you can send in php additionally. it would be better than (i+1) 

      $("#partyDetail-listview").append('<li> <img src="images/final-fantasy-7-final-fantasy-vii-6973833-1024-768.jpg"> <h2>'+ member + '</h2> <p id="'+ id +'"></p> </li>').listview("refresh");  
      console.log("appended count:" + id);

      if (member) {
        $("p#" + id).html(obj['rating']);
        console.log("full name is " + obj['name'] + " rating is " + obj['rating']);
        console.log("retrieve rating valued:"+obj['rating']+" to p#" + id);
        console.log("end of loop cycle" + id);
      }
    });
  };

  $.post("retrieveMemDetails.php", 
  {
    teamID:teamID, // data to pass into php     
    username:globalUsername,                
  },  // data to pass into php                                                                                    
  callback, 'json');
});

【讨论】:

  • 谢谢伙计,我会尽快试用代码并更新您。感谢您的帮助。
猜你喜欢
  • 2020-10-02
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 2013-08-29
  • 2020-04-28
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多