首页 > 解决方案 > 当我使用 GET 时,Ajax If else not workign

问题描述

这是我的 Ajax 函数和 JSON 数据。我想在 2 个输入字段中打印值。第一个输入字段已更新,但第二个未更新。

<select name="products" required class="form-control changeStatus"id="major_type_selected" onchange="get_inventory_check_for_order_ajax(this)">
    <option value="None">--Select a Type--</option>
    <option value="1">123</option>
    <option value="2">456</option>                                 
</select>
<input class="form-control sub_type_data"  value="0" type="number" name="wh_qty"/> 
<input class="form-control sub_type_datas" id="sub_type_datas" value="0"  type="number" name="SL_qty"/>

这是 JSON 数据:

"[{\"model\": \"inventory.productlocation\", \"pk\": 14, \"fields\": {\"location\": \"IU\", \"quantity\": 0, \"product\": 5}}, {\"model\": \"inventory.productlocation\", \"pk\": 13, \"fields\": {\"location\": \" SL\", \"quantity\": 5, \"product\": 5}}, {\"model\": \"inventory.productlocation\", \"pk\": 15, \"fields\" : {\"位置\": \"WH\", \"数量\": 6, \"产品\": 5}}]"

这是javascript代码

function get_inventory_check_for_order_ajax(ref) {

            var thisIs = $(ref);
            products = thisIs.val();

            console.log(products);


            $.ajax({
                'url': "{% url 'get_inventory_check_for_order' %}",
                'type': "GET",
                'data': {"products":products},
                'async': false,
                'success': function (data) {
                    if (data == "empty") {
                        $('#sub_type_data').html("");
                        $('#sub_type_data').append($('<option/>').attr("value", "None").text("--Select Wharehouse--").prop('selected', true).prop('disabled', true));
                    } else {
                        results = JSON.parse(data)
                        $.each(results, function(index, result){
                            console.log(result.fields.location);
                            if (result.fields.location == 'WH'){
                     thisIs.parent().next().find(".sub_type_data").val(result.fields.quantity);

                            }
                            else if (result.fields.location == 'SL'){
                                # Here the second input field's value should change
                                thisIs.parent().next().find(".sub_type_datas").val(result.fields.quantity);
                            }
                        });
                    }
                }
            });
        }

标签: javascriptajax

解决方案


在没有空关键字的情况下使用它

采用:

if (data){}  //this will run if "data" has some value otherwise else statement is encountered

推荐阅读