简体   繁体   中英

Is there a better way to deal with this JSON data

I'm just getting my feet wet with jQuery after beginning to read Sitepoint's "Novice to Ninja" but, as always, I'm left wondering if there's a better way to write the code I've come up with. As it turns out, the answer is almost always and emphatic "yes."

All these "if" statements seem ridiculous. How can I do this better? What functions should I look at to clean this up. Thanks for the help.

$('#user').change(function(){   
var user_id = $('#user').val();
$.ajax({
    type: 'POST',
    url: '../admin/billing/' + user_id,
    dataType: 'json',
    success: function(billing){
        //alert(billing.id);
        var name = '<a href="../user/view/' + user_id +'">' + billing.fname + ' ' + billing.lname + '</a><br />';
        if(billing.company_name != ''){
            var company_name = billing.company_name + '<br />';
        }else{
            var company_name = '';
        };
        if(billing.address_one != ''){
            var address_one = billing.address_one + '<br />';
        }else{
            var address_one = '';
        };
        if(billing.address_two != ''){
            var address_two = billing.address_two + '<br />';
        }else{
            var address_two = '';
        };
        var csz = billing.city + ', ' + billing.state + ' ' + billing.zip + '<br />';
        if(billing.phone != ''){
            var phone = billing.phone + '<br />';
        }else{
            var phone = '';
        };
        var data = name + company_name + address_one + address_two + csz + phone;
        $('#billing').empty().append(data);
        $('input:text').val('');
        $('#same-as-billing').attr('checked', false);
    }
});

});

Not a huge improvement but will help John Resig's Javascript Micro Templating

Generally you want to try to render everything server side but if you have no choice (data coming from an external domain) it's helpful.

You can loop through json object and create sting:

var data = [];
$.each(billing, function(key, value){
  if(value != "") data.push(value);
});
data = data.join("<br />");

But this wont work for you if you need more than just output object values (just an example). There is nothing much that you can optimize here. You can only skip some else s

var data = '<a href="../user/view/' + user_id +'">' + billing.fname + ' ' + billing.lname + '</a><br />';
if(billing.company_name != "") data+= billing.company_name+"<br />";
if(billing.address_one != "") data+= billing.address_one+"<br />";
data+= billing.city+", "+billing.state+" "+billing.zip+"<br />";
// and so on

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