doudieheng5322 2012-01-18 19:36
浏览 51

jQuery if()工作不好要求空的ajax响应

I have a form which I load in parts depending on the users selection.

When the users select a date, I search for the qtty of available stock on that date (this are seats on a train travel).

I Have 3 IF() sentences

  • First, I ask if the db response doesn't return any row (so the travel for that date haven't been created so I must create it in that moment for the costumer to reserve)
  • Second, I ask if the response is a number (I only return a number, sorry if I didn't specified that before) AND if it's bigger than zero. so I update the available qtty. So the costumer can't over buy non-existing seat.
  • Third and last, if the others fails and the qtty is zero, I just send the customer a message indicating that, the travel is full for that date, he/she must choose a different date to travel.

The code I have is this:

$.post(url,function(data){
        //********************
        //data = parseInt(data);
        alert("muestra: "+data+".");
            //3 opciones
        //si viene vacia la respuesta, es por que no encontro, reservas  o sea que nadie a reservado para la fecha solicitada
        //     lo que sigue es crear la reserva de todas formas, luego re-consultar por los valores y traer la cantidad total //podria mejorar
        //si viene con 0 es por que no existe disponibilidad para el viaje en esa fecha, tendra que intentar cambiando categoria (vagon) o fecha
        //si un numero >=1 hay disponibilidad y se crean los sliders que le permiten seleccionar la cantidad de asientos para reservar
        //TODO: cambiar al switch ....
        if(data=="false" || data==false){
        //if(data=='NaN'){
            $("#info-disponibilidad").html("No existen reservas previas, sera el primero en reservar para esta fecha. Asientos Disponibles: ");
            $("#info-disponibilidad").css("color","green");
            var myRandom=parseInt(Math.random()*99999999);  // tecnica cache buster
            //url = 'asientos-disponibilidad.php?categoria='+$('#categoria option:selected').val()+'&fecha_reserva='+$('#fecha_reserva').val()+'&rand=' + myRandom;
            url = 'crear_reservas.php?viaje='+$('#viajes option:selected').val()+'categoria='+$('#categoria option:selected').val()+'&fecha_reserva='+dateText+'&rand=' + myRandom;
            $.post(url,function(data2){
                //algo algo con la respuesta... ...
                alert("1er: "+data2+".");
            });
        }

        if(!isNaN(data) && data!=0){
        //if(!isNaN(data) && data!=0){
            alert("2do: "+data);
            //este se puede aprender facilmente al buscar el ejemplo en Jquery Ui slider
            $("#info-disponibilidad").html("Existen, "+data+" asientos Disponibles");
            $("#info-disponibilidad").css("color","green");
            //este se puede aprender facilmente al buscar el ejemplo en Jquery Ui slider
            $( "#slider-adultos" ).slider({
            //range: "min",
            min: 1,
            max: data,
            slide: function( event, ui ) {
                $( "#adultos" ).val(ui.value );
                $("#adultos").trigger("change");
            },
            stop: function(event, ui) { 
                $("#total-box").effect("highlight", {}, 2000);  
                //var max = parseInt($("#adultos").val());//usar esta variable en lugar de value (por si algo falla)
                manejoreservas(ui.value,"ninos", data);
            }
            });
            $("#slider-ninos").slider({
            //range: "min",
            min: 0,
            max: data,
            slide: function( event, ui ) {
                $( "#ninos" ).val(ui.value );
                $( "#ninos" ).trigger("change");
            },
            stop: function(event, ui) {
                $("#total-box").effect("highlight", {}, 2000);
                //$("#slider-ninos").slider( "option", "max", max );
                //var max = parseInt($("#ninos").val());//
                manejoreservas(ui.value,"adultos", data);
            }
            });
        }
        else//(!isNaN(data) && data==0  && data!=false)
        {   // && data!=false
            alert("3ro: "+data+" no disponibilidad");
            $("#info-disponibilidad").html("No existen asientos Disponibles");
            $("#info-disponibilidad").css("color","red");
        }
        });

and the php code is this:

<?php
//busca cual es la cantidad de asientos disponibles en una reserva si es que esta existe...
include('conn.php');
if (!$con)
  {
    die('Fallo conexion a la Base de datos: ' . mysql_error());
  }else{
  $categoria = $_GET['categoria'];
  //$fecha = $_POST['fecha_reserva'];
  $fecha = $_GET['fecha_reserva'];

  $sql_cant ="SELECT restante FROM reservas WHERE fecha_reserva = '".$fecha."' AND categorias_idcategorias = ".$categoria."";

  mysql_select_db("mvargas", $con);

  $result = mysql_query($sql_cant);
  $num_rows = mysql_num_rows($result);
  //echo $sql_cant;
  if($num_rows < 0){
    echo "";
  }else{


    //echo "<b>".$num_rows."</b>";
    while($row = mysql_fetch_assoc($result)){
      $foo = $row['restante'];
      $j++;
    }  
    //
    //var_dump($foo);
    echo $foo;
  }
}
?>

The last thing I have achieved, is that everything is working, but it enters the first IF displaying a message that the user will be first reservation in that date (create the travel) then it enters the third IF (else in the code shown) erasing the first message, and setting the message for the zero qtty, flashing awkwardly both messages in the screen for the user confusion.

Sorry if it's too long... here is the page for you to see: http://www.micontrol.cl/~mvargas/wordpress/wp-transatacama/reservas-rapidas/form-reservas.php

  • 写回答

2条回答 默认 最新

  • doubo4336 2012-01-18 19:45
    关注

    If I'm understanding you correctly, change the 2nd if to an else if...

    ....
    ....
                alert("1er: "+data2+".");
            });
        } else if(!isNaN(data) && data!=0){
        //if(!isNaN(data) && data!=0){
            alert("2do: "+data);
    ....
    ....
    

    It will then only run the 2nd if statement if the first one is not true.

    评论

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行