0

I am doing an simple get request to get a page which has scripts that dynamically insert content.

When I try to do

$.ajax({
   url: url,
   type: "GET",
   success: function(data, status, xhr){
      // triggered before dynamically inserted content is added
   },
   error: function(xhr, status, error) {
      console.log(error); 
   }
});

The success callback function is triggered and the data returned doesn't contain the dynamically inserted content. Is it possible to wait for it to be loaded? If so, any idea how?

4

2 回答 2

2

If i understood correctly the page you are fetching via get contains js code in it that issues other ajax requests whose completion you need to wait for before doing additional stuff. In that case, the best way is to have a callback function defined in your main page which you call from the success handler of the ajax call in your internal page.

If you have control over the content of the second site, you can include in it a script from the main domain. Code in this script should be able to call your callback function without cross domain security issues.

于 2012-07-25T20:18:34.220 回答
0

No, you need to add your content in the success callback function:

$.ajax({
   url: url,
   type: "GET",
   success: function(data, status, xhr){
      // insert dynamic content HERE
   },
   error: function(xhr, status, error) {
      console.log(error); 
   }
});

JavaScript isn't designed to "wait" because the wait takes an indefinite amount of time and it would prevent the rest of the browser from processing. If you created an infinite loop, for example, that just sits and waits, your web browser would freeze.

UPDATE

Be sure you are calling your ajax method inside the ready event. This will ensure that the document is loaded first.

$(document).ready(function(){
    // Your JS here
});
于 2012-07-25T20:01:32.003 回答