2014-04-12 38 views
0

我不明白爲什麼會發生這種情況。我正在寫一個jquery插件從我的數據庫(Mongo)中獲取記錄以返回數據。這就是代碼的樣子...jquery插件div顯示不工作沒有預先警報

(function() { 
var result1; 
var image1; 

$.fn.showRecs = function() { 

     var loadData = randomShow(); 
     var result = loadData.complete( function(data) { 

      $.each(eval(data), function(i,item){  
      result1 = item.name; 
      image1 = item.pic1; 
      if (image1 == undefined) { image1 = "face_unknown.png"; } 

     }); 

     }); 

     alert(result1); 

     this.html("<img src='http://localhost/uploads/" + image1 + "'></img>" + "&nbsp;" + result1); 


} 



function randomShow() { 

return $.ajax({ 
     type: "POST", 
     url: "http://localhost/action.php", 
     data: {'showProf' : 1, 'random' : 1 , 'limit2Show' : 1}, 
     datatype : "json", 
     }); 

} 

}(jQuery)); 

顯示「this.html」的行不顯示值,除非之前預先設置了警報。爲什麼會發生?請讓我知道擺脫它。

此外,我正在尋找附加計時器,以便它每隔n秒觸發一次,我在哪裏附加它?謝謝您的幫助。

+0

你需要在'$()',即'$(this)' – Derek

+0

中包裝'this',但是沒有幫助。我將這個插件fn稱爲$(「div」)。showRecs();來自我的主要劇本。擁有$(this)的方式與沒有相同。 – Param

+0

可能重複[如何從AJAX調用返回響應?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Liam

回答

0
try to change your ajax like: 

function randomShow() { 

return $.ajax({ 
    type: "POST", 
    url: "http://localhost/action.php", 
    async:false, 
    data: {'showProf' : 1, 'random' : 1 , 'limit2Show' : 1}, 
    datatype : "json", 
    }); 

}

}(jQuery的));

請注意,「async:false」將確保您在成功執行ajax響應時返回ajax響應。在你的情況下,它在滑動ajax,因爲它表現爲異步。

+0

我真的不希望使用「ajax:false」打破了我的插件的全部目的,因爲它必須異步加載它們,而不會影響頁面中的其餘功能。是什麼賦予了 ? – Param

+0

簡而言之,facebook/g +有一個插件,用於異步加載ajax中的共享計數。我的插件會是這樣的,所以它不應該中斷頁面中的任何事物,因爲它可以無縫地加載它們。這是如何實現的? – Param