簡體   English   中英

如果有其他條件,則根據返回的數據類型應用

[英]Applying if else condition depending on the type of data returned

我正在從php文件返回數據,該文件可以是json或其他任何文件。我想有條件地執行該功能。 這是PHP代碼-

<?php
ini_set("display_errors", 1);

require_once("db.php");

$resultnew = "SELECT DISTINCT(`item_name`) FROM item_master WHERE `item_name`='" . $_POST['key'] . "'";

$resultfinal = mysqli_query($conn, $resultnew);

if (mysqli_num_rows($resultfinal) > 0)
    {
         $sql = "SELECT * FROM `item_master` WHERE `item_name` = '" . $_POST['key'] . "' ";
    $result=mysqli_query($conn,$sql);
    while($row = mysqli_fetch_assoc($result))
    { 

        $item_name = $row["item_name"];
        $des = $row["item_description"];
        $qty = $row["item_in_qty"];
        $rate = $row["item_price"];
       $unit = $row['item_unit'];

       }
        echo json_encode(array("item_name"=>$item_name,"des"=>$des, "qty"=> $qty, "rate"=> $rate, "unit"=> $unit ));

}
else{
     echo "not ok";

}


?>

在上面的代碼中,如果數據庫中有任何匹配的值,則它將返回json值,如果數據庫中沒有此值,則將返回“不正確”。

在此我正在應用這樣的條件-

function checkitems(targetID)
{
    var items = $('#items_' + targetID).val();
    if (items != "") {
      $.ajax({
        type: 'post',
        url: 'itemcheck.php', 
        data: {key: items},
        dataType: 'json',
        success: function(data) {  

        if (data == "not ok") {

           $('#myitemmodal').modal("show");

        } else {

           var tr = $(this).closest('tr'); // here is the code for retrieving the values. i think here i need to make some changes     
            $('#price_' + targetID).val(data.rate);
            $('#size_' + targetID).val(data.des);
            $('#qty_' + targetID).val(data.qty);
            $('#unit_' + targetID).val(data.unit);
         }
       }
      });
    }
}

現在,我面臨的問題是它總是只進入else條件,而不是if條件。也許是因為我提到數據類型是json。 當我刪除數據類型:json時,它的表現不佳。 我該如何處理這種情況。讓我知道您是否還有其他需要。 提前致謝。

如您所期望的那樣,您應該返回JSON,並且"not ok"不是有效的JSON。

<?php

    ...
    if (mysqli_num_rows($resultfinal) > 0) {
        ...
        echo json_encode(
            array("data" =>
                 array("item_name"=>$item_name,"des"=>$des, "qty"=> $qty, "rate"=> $rate, "unit"=> $unit )
            )
        );
    } else {
        echo json_encode( 
            array("data" => "not_ok") 
        );
    }

然后抓住它

success: function(data) {  

    if ("data" in data && 
        typeof data.data == "string" && 
        data.data.trim() == "not ok") {

       $('#myitemmodal').modal("show");

    } else {

如果請求json,則應將“ not ok”格式化為json響應。 它可以很簡單:

{“錯誤”:“不好”}

並讓您的js測試錯誤密鑰的存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM