如何根据下拉选项选择不同的API调用

时间:2018-12-13 09:46:09

标签: javascript jquery html css api

嗨,我想在我的登录页面上添加功能,用户可以从下拉选项列表中进行选择,每个选项都有自己的api链接,具体取决于每个api决定用户是否可以登录,如何登录我可以将api调用链接到每个菜单选项吗?

<label for="Hierarchy">hierarchy</label>
<select name="hierarchy" id="hierarchy" value="">
  <option value=""></option>
  <option value="Staff">staff</option>
  <option value="Teacher"> teacher</option>
  <option value="Student">student</option>
</select>

1 个答案:

答案 0 :(得分:2)

您可以使用jQuery的.change()事件,然后使用this.value来检查选择了哪个选项,然后使用if语句运行相应的API调用。

请参见以下示例:

$("#hierarchy").change(function() { // Run this function when option selected
  let position = this.value;
  if(position == "Staff") {
    api_login('usa'/*ADD OTHER ARUGMENTS HERE*/);
  } else if(position == "Teacher") {
    api_login('france'/*ADD OTHER ARUGMENTS HERE*/);
  } else if(position == "Student") {
    api_login('uk'/*ADD OTHER ARUGMENTS HERE*/);
  } else {
    console.log("Stop/Don't run any API's");
  }
});


function api_login(country, dealer_code, userid_code, actionID = '10', VRN = '', filename = '') { /* ADD country AS A FIRST ARGUMENT */
  if (dealer_code === undefined || userid_code === undefined) {
    return false;
  }
  if (actionID === undefined) {
    actionID = '10';
  }
  var string = 'dealerID=' + dealer_code + '&salesExecID=' + userid_code + '&actionID=' + actionID + '&VRM=' + VRN + '&filename=' + filename;
  var querystring = country +'.snstest.judgeservice.co.uk/api.php?' + (string); /* CHANGE THIS LINE TO USE country */
  var error = [];

  $.getJSON(querystring, function(json) {
    var response = String(json.code);
    var message = String(json.message);
    var ident = String(json.identifier);
    var username = String(json.accountName);
    var siteName = String(json.siteName);
    console.log(json);
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="Hierarchy">hierarchy</label>
<select name="hierarchy" id="hierarchy" value="">
  <option value=""></option>
  <option value="Staff">staff</option>
  <option value="Teacher"> teacher</option>
  <option value="Student">student</option>
</select>

uk.snstest.judgeservice.co.uk/api.php? usa.snstest.judgeservice.co.uk/api.php? france.snstest.judgeservice.co.uk/api.php? so depedning what country
student=uk staff=usa teacher=france

如果您打算在下拉菜单中添加更多选项,建议您使用key作为选项值的对象,并且键的值是触发API调用的函数。

此外,使用上述代码,您可以将api_login()与通过的国家/地区一起使用。您仍然需要添加其他参数,但是由于您没有提供它们的含义,因此我没有包含它们。另外,请注意,您当前链接的URL API不适用于附加在前面的国家/地区