请帮助-我有以下代码,它在警报中返回变量'results‘。我希望在函数外部使用此变量,但无法获得回调或外部声明以成功工作。我确信我是一个木偶,所以我为这个基本的问题道歉……
<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script>
$(function () {
$.ajax({
type: 'POST',
dataType: 'jsonp',
url: 'https://creator.zoho.com/api/json/my-company-culture/view/PageFeed_Report?scope=creatorapi&authtoken=d670dc68ac0f6d7ca389e7b206a25045',
success: function (results) {
var raw_result=JSON.stringify(results);
alert(results);
}
});
});
</script>发布于 2013-11-27 05:19:38
解决此问题的jQuery 1.5+方法是使用延迟对象:
var res;
var ajax = $.ajax({
type: 'POST',
dataType: 'jsonp',
url: ...
}).done(function(results) {
// you may safely use results here
res = results;
...
});
// you cannot safely use 'res' here, only in code
// invoked via a 'done' callback on the `$.ajax` promise
console.log(res); // undefined尝试将results复制到外部作用域中的其他变量中是不正确的,除非您已经确保在AJAX调用完成之前没有其他代码尝试访问该变量。
发布于 2013-11-27 05:46:59
好吧,为什么不呢:
<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script>
function do_the_stuff(smth) {
console.log(smth);//or do whatever you want to do with this data
}
$(function () {
$.ajax({
type: 'POST',
dataType: 'jsonp',
url: 'https://creator.zoho.com/api/json/my-company-culture/view/PageFeed_Report?scope=creatorapi&authtoken=d670dc68ac0f6d7ca389e7b206a25045',
success: function (results) {
var raw_result=JSON.stringify(results);
do_the_stuff(results);
}
});
});
</script>这对我来说很好。我看不出有什么问题。
发布于 2013-11-27 05:38:27
我不确定这样做有什么好处,只是将其保存到全局定义的变量中。
var global;
$(function () {
$.ajax({
type: 'POST',
dataType: 'jsonp',
url: 'https://creator.zoho.com/api/json/my-company-culture/view/PageFeed_Report?scope=creatorapi&authtoken=d670dc68ac0f6d7ca389e7b206a25045',
success: function (results) {
var raw_result=JSON.stringify(results);
global = results;
}
});
});更好的解决方案是将它传递给您需要它转到的函数。
success: function (results) {
var raw_result=JSON.stringify(results);
doMoreThings(results);
}https://stackoverflow.com/questions/20228037
复制相似问题