Ajax成功if语句和echo mySQL查询结果

时间:2014-02-13 15:43:12

标签: php mysql ajax

我有一个Ajax脚本,每隔20秒就会在我的服务器上调用一个php文件。

然后,服务器运行一个简单的mysql查询以返回特定字段的内容。

如果该字段为空,我希望php文件回显单词“pending”,当成功处理程序捕获时将调用初始函数。但是,如果该字段不为空,则它将包含我要将用户重定向到的URL。该字段将更新从第一个呼叫开始的5秒到5分钟之间的任何位置,并且该时间无法更改。

我认为主要问题可能在于我的php文件,因为我不认为它以成功处理程序识别的方式回显数据。但是我已经详细说明了我的代码的两个部分,因为虽然成功处理程序似乎构造正确,但我并不是100%确定。

对此非常陌生,如果我没有正确解释自己,如果有人可以提供帮助,那么道歉很棒:

更新 - 为了清楚起见,我希望实现的目标如下:

Ajax调用我的php文件。

PHP文件查询数据库

如果查询的字段不包含数据,则回显ajax成功处理程序(IF)中的“待处理”字,后者又调用原始函数/ ajax调用。

如果查询的字段包含数据(将是URL),则将此结果以一种格式回显给ajax成功处理程序(ELSE),该格式将通过window.location.assign(data)重定向用户。

进一步更新

我设法使用@mamdouhalramadan和@martijn

的建议来解决这个问题

我还将setInterval更改为setTimeout,因为如果服务器运行缓慢并因此导致错误,则poll函数会导致响应堆叠。我还添加了cache:false和成功处理程序中的另一个选项,以考虑IE中略有不同的行为:

AJAX

 function poll() {

                     $.ajax({

                         url: 'processthree.php?lead_id='+lead_id,

                         type: "GET",

                         cache: false,

                         async: false,

                         success: function(data3) {

                     //alert("pending called " + data3)

                        if(data3.indexOf("pending") >-1 ){

            setTimeout(poll, 20000); 

                     }

                        else if ( (navigator.userAgent.indexOf('MSIE') != -1) ) {

                        //alert("Submit success - MSIE: " + data3);

                        parent.window.location.replace(data3);

                    }

            else{           

                         //alert("process three called " + data3)

                         window.top.location.assign(data3);

                   }

             },



             error: function(xhr, error){

                     //alert("Error");

                     //alert("Error: " + error + ", XHR status: " + xhr.status);

                 },

              });

           }

       setTimeout(poll, 20000);

PHP

$query = ("SELECT column FROM table WHERE id = '$lead_id'") or die(mysql_error());

$result = mysql_query($query);

$return = array();
while($row = mysql_fetch_assoc($result))
{
   $return = 'pending';
   if($row['column'] != '')
   {
   $return = $row['column'];
   }
}
echo $return;

1 个答案:

答案 0 :(得分:0)

我相信使用json可能会对你有帮助,更不用说它更安全,就像这样:

function poll() {
                         $.ajax({
                         url: 'processthree.php?lead_id='+lead_id,
                         type: "GET",
                         dataType: 'json',//specify data type
                         success: function(data3) {
                            if(data3.res.indexOf("pending") >-1 ){
                         //rest of the code.....

然后在你的php中:

$return = array();
while($row = mysql_fetch_assoc($result))
{
   $return['res'] = 'pending';
   if($row['column'] != '')
   {
     $return['res'] = $row['column'];
   }
}
echo json_encode($return);

注意:使用PDO或MYSQLI代替mysql,因为它已被弃用。