[英]Returning getJSON response from a function
I have a javascript file where I expect to call the same getJSON call over and over again. 我有一个javascript文件,希望在其中反复调用相同的getJSON调用。 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. 其中myjsonfunction(url)
是一个独立的函数,我可以传递URL并返回原始的getJSON数据。 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. 我已经看到了一些示例,在这些示例中,您已经在getJSON块等之外设置了一个已定义的变量。但是我似乎无法使其中任何一个起作用。
Try using .then()
, as data
is asynchronous , if could be called synchronously before response from myjsonfunction(url)
尝试使用.then()
,因为data
是异步的,如果可以在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)
})
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.