简体   繁体   English

通过调用函数使用Ajax调用rest api

[英]call rest api using Ajax by calling function

I have to call the rest API and get the response currently I am doing like this and its perfectly working fine , But I need to call this via the function and need to pass the two params which will be used in the URL and need to return the response from that function, so that I can use it the response in other classes. 我必须调用rest API并获取当前正在执行的响应,并且它工作正常,但是我需要通过函数调用此函数,并且需要传递将在URL中使用的两个参数,并且需要返回该函数的响应,以便可以在其他类中使用它。

$.ajax({
  url: "BaseURL"+param1+"/" + param2
}).then(function (data) {
  if (data.test== null)
    self.prop1(data.test);
  if (data.test2 !== null)
    self.prop2(data.test2);
  if (data.test3 !== null)
    self.prop3(data.test3)
});

Can u please suggest some way to do this , please let me know if you need any information from my side. 您能提出一些建议吗,如果您需要我的任何信息,请告诉我。

I would suggest you build the URL outside of the function: 我建议您在函数外部构建URL:

// Define URL variable 
var BaseURL = 'www.baseurl.com';
var param1 = '<param1>';
var param2 = '<param2>';
var URL = `${BaseURL}${param1}/${param2}`

function AJAXPost(RequestType, formData, URL){
    $.ajax({
      url: URL
      type: RequestType,
      data: formData
      //Test success / error
    })
}

You can create a function with both parameters and a third parameter as tyhe callback, to return the data 您可以创建一个同时带有参数和第三个参数的函数作为回调,以返回数据

function request(param1, param2, callback) {
  $.ajax({
    url: "BaseURL"+param1+"/" + param2
  }).then(function(data) {
    callback(data);
  });
}

Or with async 或与异步

const req = async (param1, param2) => {
  try {
    let data = await $.ajax({url: `BaseURL${param1}/${param2}`});
    return data;
  } catch(e) {
    console.error(e);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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