【发布时间】:2016-12-30 12:32:10
【问题描述】:
经过几天打破我的想法并尝试自己解决我的问题后,我决定寻求一些帮助。这是我的代码:
// -----------
// Global object
// -----------
window.myObj = window.myObj || {};
function getLocation(myObj) {
// Location test
// -- Mobile connection test/fix
// -- First step => Ask on client IP
$.getJSON( "//freegeoip.net/json/?callback=?", function(data) {
console.warn('Fetching Accurate JSON data...');
if (data.city !== '') {
// Log output to console
console.info('Location found from client ip');
console.info(JSON.stringify(data, null, 2));
// myObj = data;
// myObj.toString = function(data) {
// return JSON.stringify(data, null, 2);
// }
} else {
// -- Second step => Ask on server IP using server name
$.getJSON( "//freegeoip.net/json/" + window.location.host + "?callback=?", function(data) {
// Log output to console
console.info('Location found from server ip');
console.info(JSON.stringify(data, null, 2));
// myObj = data;
// myObj.toString = function(data) {
// return JSON.stringify(data, null, 2);
// }
});
}
});
return myObj;
}
console.info(getLocation(myObj));
我想要的是将 JSONP 回调的结果存储到名为 myObj 的外部对象中。
我尝试以这种方式将函数创建为闭包:
window.myObj = (function () {
// Location test
// -- Mobile connection test/fix
// -- First step => Ask on client IP
$.getJSON( "//freegeoip.net/json/?callback=?", function(data) {
console.warn('Fetching Accurate JSON data...');
if (data.city !== '') {
// Log output to console
console.info('Location found from client ip');
return data;
} else {
// -- Second step => Ask on server IP using server name
$.getJSON( "//freegeoip.net/json/" + window.location.host + "?callback=?", function(data) {
// Log output to console
console.info('Location found from server ip');
return data;
});
}
});
}());
但它每次都返回undefined...您可能会看到我的javascript技能不太好,就像我的英语一样。
提前感谢大家的帮助。
【问题讨论】:
标签: javascript jquery reactjs jsonp