简体   繁体   English

具有AJAX响应或AJAX response.response.Text的IF条件不起作用

[英]IF condition with AJAX response or AJAX response.response.Text is not working

I am developing a web page which displays an alert as soon as somebody inserts a new tuple in a database table using the same 'mesa' column that I sent in my AJAX request, so for that purpose I created a Javascript Timer in which I am constantly sending AJAX requests to check if there is a new tuple in my database table and so far the timed AJAX request are working, but when I want to condition the response with an if to see if the value of it equals to a certain value, it just completely skips it, so I am unable to display alerts even if the values that the AJAX response requests are throwing are right, so I was wondering what I could be doing wrong, I have been analyzing the code for over 2 hours and I don't seem to find the error, I even displayed alerts to verify that the response is equal to 0 or 1 which showed up that they do display them right, and I used response.responseText too , any help would he highly appreciated, thank you so much. 我正在开发一个网页,当有人使用我在AJAX请求中发送的相同'mesa'列在数据库表中插入新元组时,该网页就会显示警报,因此,我创建了一个Javascript计时器,不断发送AJAX请求以检查我的数据库表中是否有新的元组,并且到目前为止,定时的AJAX请求都可以正常工作,但是当我想对响应进行条件if以查看其值是否等于某个值时,它只是完全跳过了它,所以即使AJAX响应请求抛出的值正确,我也无法显示警报,所以我想知道自己可能做错了什么,我已经分析了2个多小时的代码,似乎没有找到错误,我什至显示警报以确认response等于0或1,这表明它们确实正确显示了它们,我也使用了response.responseText ,他将非常感谢您的帮助,谢谢你真多

This is my Javascript file 这是我的Javascript文件

var Solicitud_Comandas = [];


for (var k = 1; k <= 15; k++) {
      Solicitud_Comandas[k] = SolicitudComanda(k);

      if(!sessionStorage.getItem("rm"+k))
      {
            sessionStorage.setItem("rm"+k,false);
      }
}

function SolicitudComanda(k)
{
      return function() {
            $(document).ready(function()
            {
            $.ajax({
            type: "POST",
            url: "Consultar_Comandas_Pendientes.php",
            data: {mesa : k},
            complete: function (response, TextStatus)
            { 
                  MensajeAlerta(response,k);
      },
      fail: function (resultado,TextStatus)
      {
            alert("it didn't work because... " + resultado+ " " +TextStatus);
      }
});
});
}
}

function MensajeAlerta(response,m)
{


            if(response == 0 )
            {
                  sessionStorage.removeItem("rm"+m);
                  sessionStorage.setItem("rm"+m,false);
            }
            else if (response == 1)
            {
                  if(sessionStorage.getItem("rm"+m) == "false")
                  {
                        alert("Hay una comanda pendiente en la mesa "+m);
                        sessionStorage.removeItem("rm"+m);
                        sessionStorage.setItem("rm"+m, true);
                  } 
            }
}

Temporizador= setInterval(SolicitudDeComanda,2500);

function SolicitudDeComanda()
{ 

      $(document).ready(function(){

            for (var l =1; l<= 15; l++) {
                  Solicitud_Comandas[l]();   
            };

      });

}      

And this is the Consultar_Comandas_Pendientes.php 这是Consultar_Comandas_Pendientes.php

    <?php 
    require "Conexion.php";
    $NumeroMesa = $_POST["mesa"];
    $Platillos = 0;
    $filas = false;
    $SelectionRows = "SELECT * FROM comandapendiente WHERE mesa = '$NumeroMesa'";
    $rows = mysqli_query($con,$SelectionRows);
    while($reg = mysqli_fetch_array($rows))
    {   

        if(isset($reg["id"]))
        {
            $filas = true;
            $Platillos++;
        }
    }


    if ($filas == true)
    {

        echo true;
    }
    else
    {
        echo false;
    }

    mysqli_close($con);
    ?>

As you can see, if there is a new tuple, the AJAX response is going to be equal to either true or false which is what I question on the if statements in the Javascript code. 如您所见,如果有一个新的元组,则AJAX响应将等于truefalse ,这就是我对Javascript代码中的if语句提出的疑问。

The first issue you have is caused by using the $.ajax({ ... complete: property and assuming the first argument to the callback is your data. But it is not, it is the request object (see documentation ). Use success: instead of complete: and then you get the data as first argument to your callback function. 您遇到的第一个问题是由于使用$.ajax({ ... complete:属性,并假设回调的第一个参数是您的数据而引起的。但并非如此,它是请求对象(请参阅文档 )。使用success:而不是complete:然后将数据作为回调函数的第一个参数。

The second issue you have is caused by the PHP line: 您遇到的第二个问题是由PHP行引起的:

echo false;

This does not echo anything, because in PHP when false needs to be converted to string, it becomes the empty string, unlike in other languages, where it becomes "0" or "false". 这没有任何回声,因为在PHP中,当需要将false转换为字符串时,它将变为空字符串,这与其他语言不同,在其他语言中,其变为“ 0”或“ false”。

So you should better echo literal strings in PHP, like: 因此,您最好在PHP中回显文字字符串,例如:

echo "1";

and

echo "0";

Also, make sure PHP does not output anything else than just that 0 or 1. Specifically check that there are no blanks, tabs, empty lines... etc, before the <?php tag or after the ?> tag. 另外,请确保PHP除了输出0或1之外,不会输出其他任何内容。请特别检查在<?php标记之前或?>标记之前是否没有空格,制表符,空行...等。 If you have several such opening and closing tags, try to join them into one PHP block. 如果您有几个这样的开始和结束标记,请尝试将它们加入一个PHP块中。

For the same reason, make sure to save your PHP in UTF-8 without BOM . 出于同样的原因,请确保将您的PHP保存为UTF-8( 不带BOM) The Byte Order Mark is a three character sequence that is sometimes saved at the start of a file, in order to declare the character encoding as UTF-8. 字节顺序标记是一个三个字符的序列,有时会保存在文件的开头,以便将字符编码声明为UTF-8。 But this sequence would then also be part of the response. 但是,此序列也将成为响应的一部分。 Most editors have an option to save with or without BOM. 大多数编辑器都可以选择保存有无BOM的选项。

Some remarks on your code 关于代码的一些说明

It is a bit strange to see $(document).ready(...) inside other functions. 在其他函数中看到$(document).ready(...)有点奇怪。 Although this works fine, it is not usually done this way. 尽管此方法可以正常工作,但通常不采用这种方式。 Normally there is no reason to have it inside another function. 通常,没有理由将其包含在另一个函数中。 All is OK, if you use it once, at this position only: 一切正常,如果您使用一次,仅在此位置:

$(document).ready(function(){
    Temporizador= setInterval(SolicitudDeComanda,2500);
});

I would write false as a string when writing to local storage: 写入本地存储时,我会将false作为字符串写入:

sessionStorage.setItem("rm"+k, "false");

It works fine without the quotes, but you then rely on the fact that JavaScript converts it to that string. 它不用引号就可以正常工作,但是您随后依靠JavaScript将其转换为该字符串这一事实。 I believe your code looks better with "false" written as a string explicitly. 我相信将"false"显式编写为字符串可以使您的代码看起来更好。

Also, it seems unnecessary to call removeItem() if you are doing a setItem() right after it. 另外,如果您setItem()setItem()执行setItem() ,则似乎不必调用removeItem() setItem() overwrites any existing value with the same key. setItem()使用相同的键覆盖任何现有值。

In your tests on the response data, it would make more sense to do string comparisons, since the data returned by PHP will be string. 在测试响应数据时,进行字符串比较会更有意义,因为PHP返回的数据将是字符串。 So like: 像这样:

if(response == "0")

... and add an else to catch any unexpected value (other than "0" or "1") so you are made aware of it (via alert or something). ...并添加一个else以捕获任何意外值(“ 0”或“ 1”以外的值),以便您通过警报或其他方式了解该值。

If you have trouble with some unexpected characters preceding the value 0 or 1, and you can't get rid of those by removing the BOM and any white space in your PHP file, then there is a work-around by relaxing your test like this: 如果您在值0或1之前遇到一些意外字符时遇到麻烦,并且无法通过删除PHP文件中的BOM和任何空白来摆脱这些字符,那么可以通过放松测试来解决此问题:

if (response.indexOf('0') !== -1) 

It is also better to specify the dataType: 'text' option in your ajax call, so not to leave that to jQuery to guess. 最好在ajax调用中指定dataType: 'text'选项,以免将其留给jQuery进行猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM