Callback function with parameters

I use AJAX page methods, but I can not pass the necessary parameters:

  function getFavStatus() {
    //favs is a list of DOM <imgs> that I want to modify their img.src attribute
    for (i = 0; i < favs.length; i++) {
      PageMethods.isFavorite(favs[i].alt,setFavImg(favs[i]));
    }
  }

  function setFavImg(fav, response) {
    fav.src = response;
  }

A problem that I cannot understand is how to use the "answer" from PageMethods, and pass the DOM object to the callback function.

I also tried to do something like this:

 function getFavStatus() {
    for (i = 0; i < favs.length; i++) {
      PageMethods.isFavorite(favs[i].alt, function (response) {
                favs[i].src = response;});   
      );
    }
  }

In this case, the answer works correctly, but ialways > favs.length, because it has already repeated the loop ...

Change . My signature is PageMethods.isFavorite:

[System.Web.Services.WebMethod]
public static string isFavorite ( string p_id )

Can someone point me in the right direction?

Thank!

+3
source share
3 answers

Try the following:

PageMethods.isFavorite(favs[i].alt, 
  function (response, ctx) {
       /* success callback */
       ctx.src = response;
  },
  function(response) { /* failed callback */ },
  favs[i] /* context */);

, .

, , , . , .

.

+1

, , .

(.. ) - , .

:

function (response) {
    document.getElementById(response[0]).src = response[1];
}
+1

Brian's answer is probably the cleanest way to do this, but an alternative (if the parameter is ctxnot supported) that solves the problem ialways at the end of the loop is to use a closure to store the value i:

function createCallback(i) {
    return function (response) {
        favs[i].src = response;
    }
}

function getFavStatus() {
    for (i = 0; i < favs.length; i++) {
      PageMethods.isFavorite(favs[i].alt, createCallback(i));   
    }
  }
+1
source

Source: https://habr.com/ru/post/1783421/


All Articles