Jquery Ajax:消除冗余

时间:2018-01-20 12:10:38

标签: javascript php jquery ajax

我有一个使用Jquery(1.6)执行四个ajax请求的函数。每个ajax请求查询不同的PHP文件,并且每个get请求的成功回调都是不同的。我已经尝试制作一个通用的ajax函数,然后每次调用它,但是如果根据我得到的回复而不知道如何进行不同的成功回调。

ajax代码是脚本的一半。

function getLearner(){

// Initialize Variables to hold collected info

var lid = '';
var sName = '';
var oName = '';
var oGender = '';
var oCourse = '';
var oAccess = '';
var oLevel = '';

// Obtain the student id from the LMS and put it into a JS variable called lid

if (typeof window.GetStudentID === 'undefined'){

    lid='DATA ERROR';
    console.log('ID: '+ lid);

} else {

    lid = window.GetStudentID();
    //lid='174186' // TEST LEARNER ID
    cpAPIInterface.setVariableValue('bcID',lid); // Learner ID
    console.log('ID: '+ lid);

    if(lid == ''){

        lid='ID Not Found';
        console.log('ID: '+ lid);

    } 
}

// Obtain the student name from the LMS and put it into JS variables called oName and sName

if (typeof window.GetStudentName==='undefined'){

    oName='DATA ERROR';
    console.log('Full Name: '+ oName);

} else {

    oName = window.GetStudentName();

    if(oName == ''){

        oName='Name Not Found';
        console.log('Full Name: '+ oName);

    } else {

        sName = oName.split(', ')[1];
        oName = oName.split(', ')[1] + ' ' + oName.split(', ')[0];

        cpAPIInterface.setVariableValue('bcNameShort',sName); // First Name
        cpAPIInterface.setVariableValue('bcNameFull',oName); // Full Name

        console.log('Full Name: '+ oName);
        console.log('Short Name: '+ sName);
    }
}

// JQuery GET request for GENDER. Pass into a JS variable called oGender

$.ajax({
    url: "/pub/getgender.php?q="+lid,
    cache: false,
    success: function(response){
        oGender=response;

            if(oGender == ''){
                oGender = 'No Gender Found';
            }

        console.log('Gender: ' + oGender);

        cpAPIInterface.setVariableValue('bcGender',oGender); // Gender into Captivate        
    },
    error: function(jqXHR, textStatus, errorThrown){

        oGender='DATA ERROR';
        console.log(oGender);
        cpAPIInterface.setVariableValue('bcGender',oGender); // Gender into Captivate
    }         
});

// JQuery GET request for COURSE. Pass into a JS variable called oCourse

$.ajax({
    url: "/pub/ga.php?q="+lid,
    cache: false,
    success: function(response){
        oCourse=response;

            if(oCourse==''){
                oCourse='No Course Found';
            }
            else{
                teststring = oCourse.replace(/^\s+|\s+$/g,''); // Remove leading and trailing whitespace
                oCourse = teststring.split(" "); // Move all words into array
                oCourse = oCourse[0]
            }

        cpAPIInterface.setVariableValue('bcCourse',oCourse); // Course into Captivate
        console.log('Course: '+oCourse);       
    },
    error: function(jqXHR, textStatus, errorThrown){

        oCourse='DATA ERROR';
        console.log(oCourse);
        cpAPIInterface.setVariableValue('bcGender',oCourse); // Course into Captivate
    }         
});

// JQuery GET request for ACCESSIBILITY. Pass into a JS variable called oAccess

$.ajax({
    url: "/pub/getdisability.php?q="+lid,
    cache: false,
    success: function(response){
        oAccess=response;

            if(oAccess==''){
                oAccess='No';
            }
            else{
                oAccess='Yes';
            }

        cpAPIInterface.setVariableValue('bcAccess',oAccess); // Accessability into Captivate
        console.log('Accessibility: '+oAccess);       
    },
    error: function(jqXHR, textStatus, errorThrown){

        oAccess='DATA ERROR';
        console.log(oAccess);
        cpAPIInterface.setVariableValue('bcAccess',oAccess); // Accessability into Captivate
    }         
});

// JQuery GET request for LEVEL. Pass into a JS variable called oLevel

$.ajax({
    url: "/pub/getlevel.php?q="+lid,
    cache: false,
    success: function(response){
        oLevel=response;

            if(oLevel==''){
                oLevel='No Level Found';
            }

        cpAPIInterface.setVariableValue('bcLevel',oLevel); // Accessability into Captivate
        console.log('Level: '+oLevel);       
    },
    error: function(jqXHR, textStatus, errorThrown){

        oLevel='DATA ERROR';
        console.log(oLevel);
        cpAPIInterface.setVariableValue('bcLevel',oLevel); // Accessability into Captivate
    }         
});

}

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案(未经测试,可能包含错误):

// lid, sName, oName above
// this solves only ajax part

function setData(data, sid) {
  switch sid {
    case 'Access'.
      data = data ? 'Yes ' : 'No';
      break;
    case 'Course':
      if (data)
        data = data.replace(/^\s+|\s+$/g,'').split(" ")[0];
      break;
  }

  if (!data)
    data = 'No ' + sid + ' Found';

  console.log(sid + ': ' + data);
  cpAPIInterface.setVariableValue('bc' + sid , data); // Sid into Captivate
  return data;
}

function setError(err, sid){
  let errData = 'DATA ERROR';
  console.log(errData);
  cpAPIInterface.setVariableValue('bc' + sid, errData); // Sid into Captivate
  return errData;
}

// JQuery GET request for GENDER. Pass into a JS variable called oGender
var oGender = $.ajax({url: "/pub/getgender.php?q="+lid,cache: false})
  .done(res => setData(res, 'Gender')
  .fail(err => setError(err, 'Gender'));

// JQuery GET request for COURSE. Pass into a JS variable called oCourse
var oCourse = $.ajax({url: "/pub/ga.php?q="+lid,cache: false})
  .done(res => setData(res, 'Course')
  .fail(err => setError(err, 'Course'));

// JQuery GET request for ACCESSIBILITY. Pass into a JS variable called oAccess
var oAccess = $.ajax({url: "/pub/getdisability.php?q="+lid,cache: false})
  .done(res => setData(res, 'Access')
  .fail(err => setError(err, 'Access'));


// JQuery GET request for LEVEL. Pass into a JS variable called oLevel
var oLevel = $.ajax({url: "/pub/getlevel.php?q="+lid,cache: false})
  .done(res => setData(res, 'Level')
  .fail(err => setError(err, 'Level'));