【发布时间】:2013-02-07 09:28:05
【问题描述】:
我在这段代码中引用'url' 时不断收到此错误。
未捕获的引用错误:未定义 url。
虽然 URL 是在 ajax 上面的一个变量中明确定义的。我究竟做错了什么?
$.ajax({
url: url,
dataType: 'jsonp',
cache: true,
jsonpCallback: 'wCallback_1'
});
这是完整的代码
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(function () {
// Specify the location code and units (f or c)
var location = 'SPXX0550';
var u = 'c';
// Run the query (pull data from rss feed)
var query = 'SELECT * FROM rss WHERE url="http://xml.weather.yahoo.com/forecastrss/' + location + '_' + u + '.xml"';
var cacheBuster = Math.floor((new Date().getTime()) / 1200 / 1000);
var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&_nocache=' + cacheBuster;
});
window['wCallback_1'] = function(data) {
var info = data.query.results.item.forecast[0];
$('#wIcon').append('<img src="http://l.yimg.com/a/i/us/we/52/' + info.code + '.gif" width="34" height="34" title="' + info.text + '" />');
$('#wTemp').html(info.temp + '°' + (u.toUpperCase()));
$('#wText').html(info.text);
};
$.ajax({
url: url,
dataType: 'jsonp',
cache: true,
jsonpCallback: 'wCallback_1'
});
【问题讨论】:
-
您的 ajax 调用超出了 ready 函数的范围。因此,ajax 调用尝试在文档准备好之前执行,将
url变量呈现为未定义,因为它是在文档就绪状态执行时编译的。 -
url是ready回调的本地。为什么不将所有代码都放在回调中?此外,在您执行$.ajax时,尚未调用ready回调。
标签: javascript ajax jquery