【发布时间】:2018-03-05 23:14:43
【问题描述】:
问题:对我的 $.getJSON 请求的回调没有运行。
在页面加载时,没有任何内容记录到控制台或页面上更新,但是当函数粘贴到控制台时,它会正确执行。
jQuery:
$(function() {
$.getJSON('http://freegeoip.net/json/', function(location, textStatus, jqXHR) {
console.log("callback running");
console.log(textStatus);
console.log(jqXHR);
$('#region-name').html(location.region_name);
});
});
console.log(typeof $ !== "undefined" && $ !== null);
console.log($.getJSON != null);
函数日志之后的两个控制台日志都为真。
上述版本针对 SO 进行了缩减。这是完整的脚本。
#Geo.Coffee
$ ->
$.getJSON(
'http://freegeoip.net/json/?callback=?',
(location, textStatus, jqXHR) -> # example where I update content on the page.
console.log "callback running"
console.log textStatus
console.log jqXHR
$('#region-name').html location.region_name
$('#areacode').html location.areacode
$('#ip').html location.ip
$('#zipcode').html location.zipcode
$('#longitude').html location.longitude
$('#latitude').html location.latitude
$('#country-name').html location.country_name
$('#country-code').html location.country_code
$('#city').html location.city
$('#region-code').html location.region_code
$('container main content').append "<p>#{location.country_code}</p>"
localStorage['loc'] = location.country_code
if localStorage.loc is "US" then alert "Your From The US."
)#.fail(-> alert "fail").done( (loc) -> alert "done")
console.log localStorage.loc
console.log $?
console.log $.getJSON?
编译好的js:
(function() {
$(function() {
$.getJSON('http://freegeoip.net/json/?callback=?', function(location, textStatus, jqXHR) {
console.log("callback running");
console.log(textStatus);
console.log(jqXHR);
$('#region-name').html(location.region_name);
$('#areacode').html(location.areacode);
$('#ip').html(location.ip);
$('#zipcode').html(location.zipcode);
$('#longitude').html(location.longitude);
$('#latitude').html(location.latitude);
$('#country-name').html(location.country_name);
$('#country-code').html(location.country_code);
$('#city').html(location.city);
$('#region-code').html(location.region_code);
localStorage['loc'] = location.country_code;
if (localStorage.loc === "US") {
return alert("Your From The US.");
}
});
return console.log(localStorage.loc);
});
console.log(typeof $ !== "undefined" && $ !== null);
console.log($.getJSON != null);
}).call(this);
html:
<p id="region-name"></p>
<p id="areacode"></p>
<p id="ip"></p>
<p id="zipcode"></p>
<p id="longitude"></p>
<p id="latitude"></p>
<p id="country-name"></p>
<p id="country-code"></p>
<p id="city"></p>
<p id="region-code"></p>
正确的小提琴:http://jsfiddle.net/5DjEq/1/
【问题讨论】:
-
你能给我们看看小提琴吗?
-
你的 jsFiddle 对我有用
-
不熟悉coffeescript...我收到错误消息
Uncaught ReferenceError: textStatus is not definedjsfiddle.net/arunpjohny/fAt77/1 -
@ArunPJohny 添加了编译好的js。
-
不确定这是编译后的 js,因为回调中的
location引用了 window.location 参见 jsfiddle.net/arunpjohny/fAt77/2
标签: javascript jquery coffeescript