简体   繁体   中英

returning value from js method with ajax call to REST service

What I am trying to do is call a js method that uses ajax to call a REST service and then return that response to the original call. Sounds simple enough, but I haven't been able to find a sufficient answer here on SO to get it to work.

If async is true, I get undefined. If I set async to false, it works, but it is holding up the loading of the page. I have tried several attempts with different examples of using promises and callbacks, but just haven't been able to figure it out. I know that there is something very basic I am missing, or concept I am failing to grasp.

In this example, I am wanting to check if an item is on a persons watch list for an auction. If it is, then it will set the icon class to active so it will change the icon color and they can see that it is on their watch list. If it is not, it remains greyed out.

Each page will have a few things like this example.

Page1.php

jQuery(document).ready(function($){

var w = mgapp.checkWatchlist($id, localStorage.u_pcjid);
if(!w.error){
  $("#watchlist").removeClass('watchlist').addClass('watchlist-active');
}

});

The method is on the script.js page. The data returned from the ajax call is a JSON object.
NOTE: async is currently set to false just to get it to work.

script.js  

var mgapp = {

checkWatchlist: function($iid, $uid) {
    var $msg;
    $.ajax({
     url: 'https://somedomain/api/v1/watchlist/item/' + $iid + '/' + $uid,
     type: "GET",
     headers: {"Authorization": localStorage.u_apikey},
     contentType: 'application/json',
     async: false
  }) 
  .done(function(data){
      $msg = data;
  })
  .fail(function(data){
    $msg = data;
  });   
 return $msg;      
}

}

I am sure I will need to have a callback function or something, but none of the attempts I have made with those have worked.

Just to clarify. All the code is working as is, it is just not working asynchronously. What I am wanting is to have async set to true so that i am making an actual asynchronous call so that this is not holding up the loading of the page. I need the value returned from the ajax call available to the var on Page1.php.

Thanks in advance.

If figured it out.

    var w = mgapp.checkWatchlist($id, localStorage.u_pcjid).done(function() {
    if(!w.responseJSON.error){
      $("#watchlist").removeClass('watchlist').addClass('watchlist-active');
    }
})




  checkWatchlist: function($iid, $uid) {
    return $.ajax({
     url: 'https://somedomain.c9.io/api/v1/watchlist/item/' + $iid + '/' + $uid,
     type: "GET",
     headers: {"Authorization": localStorage.u_apikey},
     contentType: 'application/json'
  }) 
},

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