lin
lin

Reputation: 221

simplify if statement in several AJAX

I need to use the same if..else to deal with every AJAX data in my code.

$.ajax({
    url: "api/aall.json",
    dataType:'json',
    type: 'GET',
    data: "data",
    cache: false,
    ifModified: true,
    success: function getData(data){
        console.log(data);    
        for(var i=0;i<7;i++){
            // if...else
        }
    });

There are several AJAX get differnt:

$.ajax({...});
$.ajax({...});
$.ajax({...});
$.ajax({...});

if...else code:

            if(MainClass_Code=="PD" || MainClass_Code=="CD"){
                newsKindRepalce = "aipl";//news
            }else if(MainClass_Code=="PF" || MainClass_Code=="JF"){
                newsKindRepalce = "aopl";//international
            }else if(MainClass_Code=="CU"){
                newsKindRepalce = "acul";//culture
            }else{
                newsKindRepalce = "acn";//artist 
            }

It's would be very heavy when I use if...else in my all AJAX to deal with data, how can I do to simplify this?

Upvotes: 0

Views: 63

Answers (1)

xianshenglu
xianshenglu

Reputation: 5359

change your if else to this:

const code = { PD: "aipl", CD: "aipl", PF: "aopl", JF: "aopl", CU: "acul" };

newsKindRepalce = code.hasOwnProperty(MainClass_Code)
  ? code[MainClass_Code]
  : "acn";

Upvotes: 1

Related Questions