2012-10-16 49 views
1

我試圖使用從JSON調用獲得的值動態添加標題到許多圖像。Jquery添加標題屬性與來自JSON調用的數據

這是我迄今爲止

$(".watch_view img").each(function() { 
$.ajax({ 
    url: 'http://gdata.youtube.com/feeds/api/videos/T2aMBeeM4yw?v=2&alt=jsonc', 
    dataType: 'json', 
    success: function(json) { 
    song_title = json.data.title;// song title is retrieved without issue       
    } 
    }); 

    alert(song_title); //this to be removed 
    //the title attr below is only added when the above alert is in place  
    $(this).attr('title', song_title); 
    $(this).attr('alt', "This works everytime"); 
    }); 

現在上述作品,但只有當我通過添加不必要的警告「停止」的過程 - 我只能猜測,代碼在它從JSON調用(?)中檢索數據之前正在執行,並且警報使其能夠趕上。

我想我需要另一個函數,在JSON調用之後執行,或者讓代碼進入'成功'函數,但我不確定如果在這種情況下如何保留'this'元素。

幫助和建議非常感謝。

感謝

克里斯

+0

SUCCESSS是溫控功能!你有沒有試過在成功中使用$(this)。 AFAIR它不應該是一個問題 –

+0

它不會在成功內部拋出一個錯誤(不管它是什麼),但它不會添加標題attr。該位置的警報顯示檢索到正確的數據。 – Chris

回答

1

請記住,AJAX代表了異步JavaScript。這意味着瀏覽器在與服務器通信正在進行時不會無響應。

當你調用$.ajax(...)功能,腳本後繼續,不等待響應(你可以將其配置爲等待,但那麼這將是一個同步調用)。

當服務器成功返回,你應該到該事件做出響應,從而,你的反應處理代碼必須在success函數體:

$(".watch_view img").each(function (index,element) { 
    $.ajax({ 
     url: 'http://gdata.youtube.com/feeds/api/videos/T2aMBeeM4yw?v=2&alt=jsonc', 
     dataType: 'json', 
     success: function (json) { 
      song_title = json.data.title; // song title is retrieved without issue       
      $(element).attr('title', song_title); 
      $(element).attr('alt', "This works everytime"); 
     } 
    }); 

}); 

在你的舊代碼,警報是由服務器之前到達回。當你放置一個斷點,它的工作,因爲有足夠的時間用於服務器返回答案,而你正在做你的人時處理:)

更新

此外,你應該知道thissuccess回調指的是返回的數據,覆蓋each的預期this(這將是迭代的元素)。您必須實際聲明each呼叫的參數,以便您可以在成功呼叫中引用它們。

+0

在成功內部移動它不會返回任何屬性(即使對於固定的alt屬性也不會) – Chris

+0

您能更具體嗎?你剛剛在你的問題中說過,'song_title = json.data.title;'工作正常。什麼具體不工作? –

+0

對不起 - 如果我有警報(歌曲標題),它會顯示正確的數據,但屬性保持空白。 – Chris

0
$(".watch_view img").each(function() { 
$.ajax({ 
    url: 'http://gdata.youtube.com/feeds/api/videos/T2aMBeeM4yw?v=2&alt=jsonc', 
    dataType: 'json', 
    success: function(json) { 
     song_title = json.data.title;// song title is retrieved without issue 

     $(this).attr('title', song_title); 
     $(this).attr('alt', "This works everytime");       
    } 
    }); 
}); 

您需要正確使用成功回調。希望有所幫助。

回調用於異步JavaScript,否則你會得到競爭條件(你所看到的)。

0

ajax調用是異步的,這意味着當您設置標題時服務器仍在處理您的請求。當您放置不需要的警報時,您暫停客戶端一段時間,然後服務器回答請求,這就是爲什麼它可以工作。

如果您將代碼置於成功之中,如上所述,它將按預期工作。

0

你可以試試這個

var _song_title = '' 
$(".watch_view img").each(function() {  
$.ajax({ 
    url: 'http://gdata.youtube.com/feeds/api/videos/T2aMBeeM4yw?v=2&alt=jsonc', 
    dataType: 'json', 
    success: function(json) { 
    _song_title = json.data.title;// song title is retrieved without issue       
    } 
    }).done(function(){ 
     alert(_song_title); //this to be removed 
    //the title attr below is only added when the above alert is in place  
    $(this).attr('title', _song_title); 
    $(this).attr('alt', "This works everytime"); 
    });