简体   繁体   中英

Call a function on ajax success call back

Below is my script

function allresultscount(thisurl) {
$.ajax({
type: "GET",
dataType: "xml",
url: thisurl,
success: function(data) {
    if ($(data).find('atom\\:entry, entry').length !== 0) {
        $(data).find('atom\\:entry, entry').each(function() {
            countall++;
        });
    }
    $("#resultscount").text(countall);
    var pagecount = countall / 2;
    for (var i = 1; i <= pagecount; i++) {
        $('<a class="page_link" onclick="formurl(' + i + ')" longdesc="0" style="display: inline-block;">' + i + '</a>').insertBefore('.next_link');
    }
}
});
}
function formurl(i) {
   alert(i);
}

Here am trying to call a function formurl() in ajax success callback. Both functions are in document ready.

But am getting formurl() undefined error. How cal I do this?

You can but they must be called within the scope of the ready() method otherwise they lose scope when the ready() method exits.

For example, the code below will work:

$(document).ready(function(){
  function formurl()
  {
    alert('Bar');
  }

  formurl(); // still in the scope of the ready method
});

After you ajax is complete, your new elements are rendered in DOM. Now you are outside the ready() event. In your case, you could define your function outside ready() event

function formurl()
      {
        alert('Bar');
      }
$(document).ready(function(){

     // fire ajax here
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM