2011-08-03 35 views
0

直升機IM 試圖檢查如果HTML被附加到ID的HTML,即時通訊不知道關於JavaScript來做到這一點的最好辦法,繼承人片斷什麼我已經到目前爲止檢查阿賈克斯成功追加與jQuery

var appendstatus= 0; 

$.ajax({ 
    type: "GET", 
    url: params['content'], 
    dataType: 'text', 
    success: function(data) { 
     // append the html 
     $(params["id"]).append(data); 
     // is this the right way to check it ? 
     appendstatus= 1; 
    } 
}); 

// got an 0, so its not global? 
console.log(appendstatus); 
// do some jobs after the html is appended on the div id 

問題是什麼是查一些數據在這種情況下追加的最佳方式?

感謝幫忙

亞當·拉馬丹

回答

2

因爲你的AJAX請求是異步,在console.log()發生接收到響應之前

任何依賴成功響應的代碼都必須放置在success:回調中(或從中調用)。

執行順序:

// STEP 1: declare and initialize the variable 
var appendstatus= 0; 

    // STEP 2: send the asynchronous request 
$.ajax({ 
    type: "GET", 
    url: params['content'], 
    dataType: 'text', 
    success: function(data) { 

      // STEP 4: The response was received, so this code runs. 
     $(params["id"]).append(data); 

     appendstatus= 1; 

     console.log('appendstatus from callback:', appendstatus); 
    } 
}); 

    // STEP 3: log to the console, because we're not waiting for the response 
console.log(appendstatus); 
0

如果成功,函數被調用,這意味着AJAX請求是succesfull,你獲得了數據。

此時您可以檢查數據,看它是否包含您期望收到的數據。

之後,你依靠一些非常安全的功能,通過ID找到一個元素並使用jQuery append方法,所以最多你可能想檢查jQuery通過ID傳遞找到正確的元素...然後你應該很確定數據已被追加。由於該數據包含DOM節點(您正在追加它們),因此您可以檢查是否再次使用jQuery函數找到這些元素,但這對我來說是偏執狂:D。

1

成功是一個回調函數,它在ajax操作成功時運行。代碼的其餘部分運行,回調函數將空閒,直到收到成功爲止。

要檢查是否添加了HTML,你可以簡單地使用:

alert($(params["id"]).append(data).html()); 

這會提醒你該元素的HTML代碼。您也可以使用console.log of course。