if else condition in jquery ajax response

时间:2016-11-09 06:54:55

标签: php jquery ajax

I have one Ajax function which is running properly.but i want when my Ajax response is

<h3>No Couriers found near by you.please select another location</h3>

i want to display some error message else i want to display another map div in else condition. but every time when i hit Ajax only else condition is working..but when i alert response and see the output it shows this message when

<h3>No Couriers found near by you.please select another location</h3>

but still it not comes in if condition..can anyone help me to do this....

<script>
$('#weight0,#weight1,#weight2,#weight3').click(function() {
    var checked = $(this).is(':checked');
     if($(this).is(":checked")) { 
        $.ajax({
          type: "POST",
          url: '<?php echo Router::url(array("controller" => "Orders","action" => "searchCourier")); ?>',
          data: {
              frmlat: $("#PoolLatitude").val(),
              frmlong: $("#PoolLongitude").val(),
              mylocation: $("#PoolLocation").val()
          },
          dataType: "html",
          success: function(response) {  
          alert(response);
            if(response =="<h3>No Couriers found near by you.please select another location</h3>"){
              alert(thanks);
            } else {
                $('#map_canvas').css('display', 'none');//used to hide map after ajax success response.
                $("#load_map").html(response); 
            }
          }, 
          complete: function() {
              $('.spinicon').hide();
          }
        });
    } else {
            $("#secretcode").val("");
        }    
});
</script>

2 个答案:

答案 0 :(得分:0)

在你的php脚本中,返回一个布尔标志而不是一个字符串:

<?php
if (some_condition) {
    $return = true;
} else {
    $return = false;
}
die(json_encode(array('return' => $return)));

在ajax的成功中:

...
dataType: 'json',
success: function(data) {
    if (data.return) {
        alert("return is true");
    } else {
        alert("return is false");
    }
},
...

希望它有所帮助。

PS:使用Json Encode轻松解析响应和访问值。

答案 1 :(得分:-1)

首先,我建议您使用状态进行ajax响应,例如:

1 for success
0 for failure 

根据您的陈述,您的回复是正确的:

alert(response);

然而,您必须检查是否有<h3></h3>标记的回复。

在您的代码中,主要问题是,您在alert alert(thanks);中使用不带引号的字符串,这将在控制台中返回undefined thanks并视为变量。

这应该是alert("thanks");

还有一个建议,当您在Ajax或任何其他脚本中没有获得成功时,最好检查浏览器控制台,这将有助于您找到错误。