我已經開始了我的第一個AJAX項目,並且我正在嘗試編寫雙AJAX函數,其中第一個函數的輸出字符串(「venue_ID」)被第二個AJAX函數用於輸出字符串(img_Url)。但我沒有取得任何成功。對於我的代碼下面的任何建議將不勝感激;執行雙AJAX調用
$(function(){
var api_url = 'https://api.foursquare.com/v2/venues/search?ll=4.89996,114.928457&client_id=DKVNHNM2I15Y0TF1RNAEF1FPQHJPCCUPHBMJKGFHXUQITWHC&client_secret=XLCPTHFDAVNTUUAOCMNDQLWAS4TXZOGAXV5A2L1AAK5QNJZS&v=20131016&query=bake+culture';
var $info = $('#info');
$.ajax({
type: 'GET',
url: api_url,
data: {format: 'json'},
dataType: 'json',
success: function (info) {
var response = info.response.venues[0];
var venue_id = response.id;
console.log('success', info);
$info.append(venue_id);
var $pic = $('#pic');
var baseUrl = 'https://api.foursquare.com/v2/venues/';
var fsParam = '/?client_id=DKVNHNM2I15Y0TF1RNAEF1FPQHJPCCUPHBMJKGFHXUQITWHC&client_secret=XLCPTHFDAVNTUUAOCMNDQLWAS4TXZOGAXV5A2L1AAK5QNJZS&v=20131016';
var picUrl = baseUrl + venue_id + fsParam;
$.ajax({
type: 'GET',
url: picUrl,
data: {format: 'json'},
dataType: 'json',
success: function (pic) {
var venue_data = pic.response.venue;
var img_url = venue_data.bestPhoto.prefix + '192x144' + venue_data.bestPhoto.suffix;
console.log('success', pic);
$pic.append(img_url);
}
});
}
});
});
<html lang='en'>
<head>
<title>AJAX Demo</title>
</head>
<body>
<div>
<h4>AJAX Demo</h4>
<div id="info"></div> <!-- To test 1st AJAX output -->
<div id="pic"></div>
</div>
<div><img src="pic"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="js/source.js"></script>
</body>
</html>
'var venue_id'只在回調中定義,所以它不能在外面訪問。但即使你解決了這個問題,它仍然無法工作,因爲Ajax請求是異步的。 –
[爲什麼我的變量在函數內部修改後沒有改變? - 異步代碼引用](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) –
可能的重複[如何在.then()鏈中訪問先前的承諾結果?](https://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-鏈) –