2013-01-21 65 views
-3

Possible Duplicate:
Use variable outside the success function from an ajax/jquery call獲取變量之外的功能jQuery的

我想獲得一個JSON查詢沒有成功之外的變量:

$(document).ready(function(){ 
    $.getJSON("https://gdata.youtube.com/feeds/api/users/diasporaduo/uploads?v=2&alt=jsonc",function(json){ 

    videoid = json.data.items[0].id; 
    }); 

    alert(videoid) 
}); 

+2

任何人都保持計數?我們每天都會收到幾百萬個這樣的問題!* –

+0

您是否嘗試過搜索? ... @JosephSilber提到這個每天都會被問到。 AJAX中的第一個'A'是用於異步的 – charlietfl

+0

對不起。我已經搜索,但沒有運氣。也許我會重新編寫我的整個代碼。謝謝你的回答 –

回答

1

你可以使用異步標誌:

async (default: true)

Type: Boolean By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

那麼你的代碼示例是:

var videoid; 
    $.ajax({ 
     url: 'https://gdata.youtube.com/feeds/api/users/diasporaduo/uploads?v=2&alt=jsonc', 
     type: 'GET', 
     async: false, 
     success: function (json) { 
      videoid = json.data.items[0].id; 
     } 
    }); 
    alert(videoid); 

提琴手:http://jsfiddle.net/5hE7n/

+2

讓我反駁一下:你*不應該使用'async'標誌。當所有其他操作失敗時,應該使用同步請求作爲最後的手段。 –

+0

謝謝,但仍然得到這個:TypeError:json.data是undefined –

+0

你看過提琴手樣本,我張貼 – Stefan