简体   繁体   English

jQuery AJAX URL剩余路径参数

[英]JQuery AJAX URL Rest path parameters

I have a Rest service on /users/{userId}/orders/{orderId} (please note the path parameters) and I want to call it from JQuery. 我在/ users / {userId} / orders / {orderId}上有一个Rest服务(请注意路径参数),我想从JQuery调用它。

I could do it simply concatenating the ids like so: 我可以这样简单地将id连接起来:

$.get(
    'users/' + 1234 + '/orders/' + 9876,
    function (data) {
        //do something with the response
    }
);

But this doesn't seem like a very correct way of doing it (although it does the job). 但这似乎不是一种非常正确的方法(尽管它确实可以做到)。

Is there a better way of passing these path parameters on the URL of a JQuery AJAX call? 有没有更好的方法在JQuery AJAX调用的URL上传递这些路径参数?

* just to clarify, my concern is more with the concatenation of the string. *只是为了澄清,我更关心的是字符串的串联。 I wonder if there's a better way to construct the url without concatenating strings. 我想知道是否有更好的方法来构造不连接字符串的url。 Perhaps string formatting would be better? 也许字符串格式化会更好?

I think Template literals is the neatest way to proceed here: 我认为Template文字是在这里进行的最简洁的方法:

$.get(
    `users/${userId}/orders/${orderId}`,
    function (data) {
        //do something with the response
    }
);

You can make a function to make this request : 您可以创建一个函数来发出此请求:

function makeOrderRequest(userId, orderId, sucessCallback) {
    $.get('users/' + userId + '/orders/' + orderId, successCallback);
}

And then call it when you need : 然后在需要时调用它:

makeOrderRequest(1234, 8796, function(data){
     //do stuff
});

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

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