Jquery / JavaScript - 从window.location中删除部分URL并用作变量

时间:2017-09-01 01:07:39

标签: javascript jquery ajax

我有以下代码段调用我的API并返回一些JSON

var authorizationToken = "xxxxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
  $.ajax($.extend({}, {
    type: 'GET',
    dataType: "json",
    success: function(data) {
      $('.Name').html(data.user.name);
      $('.Email').html(data.user.email);
      $('.Address').html(data.user.teams[0].name);
    },
    url: "https://api.myapi.com/" + endpoint,
    headers: {
      "Authorization": "Token token=" + authorizationToken,
      "Accept": "application/vnd.myapi+json;version=2"
    }
  },
  options));
}
myapiRequest('/users/' + 'usersID' + '?include%5B%5D=contact_methods&include%5B%5D=teams'); //This is where my userID variable will be called

我想补充更多内容......

var currentLocation = window.location; // https://myapi.com/users/PLLFFR6
var usersID = PLLFFR6

获取当前的Windows URL并删除用户ID' PLLFFR6' out并使用它作为我的URL后面的变量始终遵循相同的模式,/ users / ID是我想要仅使用的ID部分

myapiRequest('/users/' + 'usersID' + '?include%5B%5D=contact_methods&include%5B%5D=teams');

2 个答案:

答案 0 :(得分:1)

如果您的网址采用split格式,那么您可以根据/ <script> window.onload = function () { test(); } function test() { var url = "https://myapi.com/users/PLLFFR6".split("/"); url = url[url.length-1] alert(url); } </script> 网址并获取最后一个数组元素。示例如下:

var usersID = location.pathname.split('/').pop()

答案 1 :(得分:0)

你的意思是这样......

$.ajax

我还会为这些查询参数使用data myapiRequest(`/users/${usersID}`, { // or "'/users/' + usersID" if you don't like template literals data: { include: ['contact_methods', 'teams'] } }) 属性,即

{{1}}