[英]How to get JSON result from an API call using jQuery(or Javascript) in a non-Ajax way?
I am new to JS an jQuery. 我是JS jQuery的新手。 And I am trying to build a key-value map from an API call which returns an array of key-value pairs.
我正在尝试通过API调用构建键值映射,该API返回一个键值对数组。
[{"key":"191","value":244}, ... , {"key":"920","value":130}]
I came up with this ajax code. 我想出了这个ajax代码。 But following code will need the map constructed from loadMap.
但是以下代码将需要从loadMap构造的地图。 How to change it to non-ajax way that the "followingFunction" runs after loadMap finishes>
在loadMap完成后如何将其更改为“ followingFunction”运行的非ajax方式>
var mp = {};
(function loadMap() {
$.ajax({
type: 'GET',
url:'http://localhost:8080/xxx/api?start_date=2014-10-01&end_date=2014-11-01',
dataType: "json",
success: function(arr){
var out = "";
for(i = 0; i<arr.length; i++) {
mp[arr[i].key] = arr[i].value;
}
}
});
}());
//followingFunction which needs the information from mp
You can solve this in two different ways. 您可以通过两种不同的方法解决此问题。
1) Execute followingFunction
at the end of your success
callback: 1)在
success
回调的末尾执行followingFunction
:
var mp = {};
function loadMap() {
$.ajax({
type: 'GET',
url:'http://localhost:8080/xxx/api?start_date=2014-10-01&end_date=2014-11-01',
dataType: "json",
success: function(arr){
var out = "";
for(i = 0; i<arr.length; i++) {
mp[arr[i].key] = arr[i].value;
}
followingFunction();
}
});
};
loadMap();
2) Set the async
flag to false
(by default this flag is true
). 2)将
async
标志设置为false
(默认情况下,此标志为true
)。 This will result in blocking call with synchronous execution: 这将导致阻塞调用并同步执行:
var mp = {};
function loadMap() {
$.ajax({
type: 'GET',
url:'http://localhost:8080/xxx/api?start_date=2014-10-01&end_date=2014-11-01',
dataType: "json",
async: false,
success: function(arr){
var out = "";
for(i = 0; i<arr.length; i++) {
mp[arr[i].key] = arr[i].value;
}
}
});
};
loadMap();
followingFunction();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.