I have a javascript file where I expect to call the same getJSON call over and over again. For example:
$(document).ready(function() {
$('#validate').click(function() {
var url;
url = 'http://myurl';
$.getJSON(url, function(data) {
if (data[0].response.status === 'ok') {
$('#validate_text').html("data validated");
} else {
$('#validate_text').html("data Not Valid");
}
});
});
});
This works I would like to refactor this to something like:
$(document).ready(function() {
$('#validate').click(function() {
var url;
url = 'http://myurl';
data = myjsonfunction(url);
if (data[0].response.status === 'ok') {
$('#validate_text').html("DLS / NTS Validated");
} else {
$('#validate_text').html("DLS / NTS Not Valid");
}
});
});
where myjsonfunction(url)
is a standalone function I can pass the URL and it returns the raw getJSON data. I have seen a few examples where you set a already defined variable out side the getJSON block etc. but I can't seem to get any of these to work.
Try using .then()
, as data
is asynchronous , if could be called synchronously before response from myjsonfunction(url)
$(document).ready(function() {
$('#validate').click(function() {
var url;
url = 'http://myurl';
data = myjsonfunction(url);
data.then(function(response) {
if (response[0].response.status === 'ok') {
$('#validate_text').html("DLS / NTS Validated");
} else {
$('#validate_text').html("DLS / NTS Not Valid");
}
}, function err(jqxhr, textStatus, errorThrown) {
console.log(erroThrown)
})
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.