0

在我的测试站点上,我试图在用户切换视频之前使用 AJAX 加载一些关于视频的文本,然后在 ajax 成功返回后输入文本。

我需要检查 AJAX 是否已成功返回并且 javascript 函数是否可用。我怎样才能检查这个?

一旦加载了 AJAX 并且一旦 javascript 函数可用,我就可以单独运行一个函数,但我不知道它们会以哪个顺序出现。

4

1 回答 1

1

你可以对事件和回调做一些事情。我仍然不确定您所说的“功能已可用”是什么意思,但这是我脑海中浮现的一些东西,应该可以帮助您入门。

// Check if all conditions are complete.
function completionChecker(limit, callback) {
  // Private count variable will outlast scope due to closure.
  var count = 0;
  // Return a callback for the event.
  return function(event) {
    if(++count == limit) { 
      // Call the callback supplied.
      callback(); 
      // Remove the event listener, we've reached the limit.
      this.removeEventListener("finished", arguments.callee, false); 
    }
  }      
}

// Some function to perform when everything is complete.
function myFunc() { /* Do stuff */ }

// Create a custom event.
var myEvt = new CustomEvent("finished");
// Add a listener to the document. After 2 "finished" events, call myFunc.
document.addEventListener("finished", completionChecker(2, myFunc), false);

// Now in your ajax success callback, and wherever your other function 
// has "become available", fire the "finished" event.
document.dispatchEvent(evt);
于 2012-12-21T01:08:11.600 回答