2010-06-29 161 views
2

我的代码尝试重新填充选项并选择一个元素。 问题是填充很多任务重新填充3个选择框。我的方法控制返回,但是当我尝试选择时,选项尚未填充。这种情况发生在较慢的系统/浏览器中。 (特别是在IE)有没有办法来防止这种使用jQuery或什么?当所有选项加载/或正在加载时,浏览器是否触发了任何事件?这似乎是因为浏览器有时需要时间来激活选项,但方法控制已经返回。处理延迟填充选择选项

function myMethod() { 
    populateOptions(); 
    if(document.getElementById('Id').options[index].text==existId){ 
     $("#Id").val(existId); 
    } 
} 

function populateOptions() { 
//Make ajax call 
    // repopulates options 
} 
+1

请发布AJAX代码。 – joshperry 2010-06-29 13:34:56

回答

1

由于AJAX调用都是异步的,你需要移动你的价值分配后运行用于填充您的select代码。否则,值分配发生在响应返回之前。

我假设任何代码填充select设置为运行收到响应。因此,在代码之后放置您的值选择应该可以解决问题。

(换句话说,它会去populateOptions()功能。)

除此之外,这是很难提供一个解决方案,没有看到你的代码。


编辑:下面是如何这可能是工作的几个例子。其中任何一项都会比请求中的设置async: false更好。

您可以将需要等待响应的代码放入success:回调中。

function populateOptions() { 
    $.ajax({ 
     url: "some/path", 
     success: function(resp) { 
      // Place ANY code that needs to wait for the response in here. 
      // This way it will not run until the successful response is received. 
     } 
    }); 
} 

或者你可以将需要等待另一个函数内部的响应,并调用它从success:回调中的代码。

function populateOptions() { 
    $.ajax({ 
     url: "some/path", 
     success: function(resp) { 
       // Call this function when the successful response is received. 
      successFunction(resp); 
     } 
    }); 
} 
function successFunction(resp) { 

    // Place ANY code that needs to wait for the response in here. 

} 

或者说,如果populateOptions()应以不同的方式重复使用,所以你需要一个不同的回调,可以从将在success:回调内部调用另一个函数传递一个函数。

function myMethod() { 
     // Send a function as an argument when you call populateOptions() 
    populateOptions(function(resp){alert(resp);}); 

    // Code that does NOT need to wait can still go here 
} 
function populateOptions(callback_fn) { // Receive the function that was sent 
    $.ajax({ 
     url: "some/path", 
     success: function(resp) { 
       // Call the function that was sent 
      callback_fn(resp); 
     } 
    }); 
} 

或采取上述同样的例子,你实际上可以使用在通过为success:回调函数。

function myMethod() { 
     // Send a function as an argument when you call populateOptions() 
    populateOptions(function(resp){alert(resp);}); 

    // Code that does NOT need to wait can still go here 
} 
function populateOptions(callback_fn) { // Receive the function that was sent 
    $.ajax({ 
     url: "some/path", 
     success: callback_fn(resp) // Now the function passed is the callback 
    }); 
} 
+0

是的。就像你说的,一旦我们收到响应,我们在populateOptions()中填充select和thats。所以populateOptions()返回所有操作的控制权完成。但有时浏览器需要时间来填充选项。这与浏览器一致。如果浏览器快速运行, – 2010-06-30 06:03:25

+1

@Jigar - 你说*“populateOptions()所有操作的返回控制都完成了”*,但是当涉及到一个AJAX请求时这不是真的。一个AJAX请求(默认情况下)允许代码在它得到响应之前继续运行。因此,在选项填充之前,控件会返回。这是常见的情况。试着移动你的代码在populateOptions()中选择一个值,然后在填充的代码之后。或者用'populateOptions()'的代码编辑你的问题。 – user113716 2010-06-30 11:42:57

+0

@Jigar - 问题解决了吗? – user113716 2010-08-24 18:19:43