简体   繁体   中英

Jquery Change Table Value Coming from AJAX call

Hi I am building a table with ajax from a response JSON. So, If in my response data there is a price object. If the price is null, I want to show it as 0.

Here is my AJAX code -

    $(document).ready(function(){

var url ="data/response.json";
var data=""; 
coAjax(url, data, function(result){
  var availableProductsList = result.response.availableProducts;
  var terminalProductsList = result.response.availableProducts;
  console.log(availableProductsList);
  var output="<tbody>";

        for (var i in availableProductsList){ 
           output += "<tr><td>" 
                    + result.response.availableProducts[i].productId + 
                    "</td><td>" 
                    + result.response.availableProducts[i].productName + 
                    "</td><td>" 
                    + result.response.availableProducts[i].quantity + 
                    "</td><td>" 
                    + "<div class='replace-split-key-tbl-inputbox'>" + "<input type='text' class='form-control key-input key-input-tbl' id="+ result.response.availableProducts[i].productId +">" + "</div>" + 
                    "</td><td><span class='availableFeaturesPriceCol'>"+ result.response.availableProducts[i].price +"</span></td></tr>";

        console.log(result.response.availableProducts[i].price);

        }

        output+="</tbody>";
 $("#addfeaturesOrderTbl").append(output);
 $("table").addClass("table");
});
});

function coAjax(url, data, handleData) {
    $.ajax({
    url:url,
    dataType: 'json',
    contentType: 'application/json',
    data:JSON.stringify(data),
    success:function(result) {
        handleData(result); 
    }
  });
}

For the price column, if the price is null I want to show it as 0. This is the code to get the price result.response.availableProducts[i].price . Please help.

您可以在其后添加逻辑OR( || )运算符 ,因此,如果它是虚假的,它将使用零代替

result.response.availableProducts[i].price || 0
var price = result.response.availableProducts[i].price;
price != null ? output+=`<td>${price}</td>` : output+="<td>0</td>";

It's

var price = result.response.availableProducts[i].price;
           var priceFinal;
           if(price != null){
                priceFinal = price;
           }else{
                priceFinal = 0;
           }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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