2012-12-12 26 views
5

FISSO! GRAZIE! Vedere "Codice corretto" di seguito.jQuery Valore restituito non definito

L'obiettivo è recuperare i dati dalla finestra di dialogo. Ho visto molti articoli, ma non sono riuscito a far funzionare nessuno di loro, quindi ho deciso di utilizzare un servizio Web per passare i dati avanti e indietro tra la finestra di dialogo e la pagina sottostante.

Tutto il codice è a posto tranne il codice che legge i valori provenienti dal servizio web. Riesco a vedere nel debugger che i dati vengono passati di nuovo, ma quando torno al chiamante, i dati restituiti non sono definiti.

jQuery chiama getLocal chiama AJAX, ottiene buoni dati indietro, ma quando ritorna alla funzione che lo chiama (verbListShow), il valore restituito è "indefinito".

Questo accade in una pagina ASP.NET scritta in gran parte in jQuery e apre una finestra di dialogo jQuery.

function getLocal(name) { 
    $.ajax({ 
     type: "POST", 
     async: false, 
     url: "WebServices/FLSAService.asmx/GetLocalVariable", 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     data: JSON.stringify({ name: name }), 
     success: function (data) { 
      var rtn = data.d; 
      return rtn; 
     } 
    }); 
} 

Il codice sopra riportato funziona, ma quando chiamato, rtn non è definito. Ecco il chiamante:

function verbListShow(dutyNumber) { 

    $('#dlgDutyList').dialog({ 
     modal: true, 
     show: "slide", 
     width: 250, 
     height: 250, 
     open: function (event, ui) { 
      setLocal("DUTYNUMBER", dutyNumber); 
     }, 
     buttons: { 
      "Select": function() { 
       var id = getLocal("VERBID"); // <*** Returns undefined 
       var verb = getLocal("VERB"); // <*** Returns undefined 
       $.ajax({ 
        type: "POST", 
        async: false, 
        url: "WebServices/FLSAService.asmx/SetDuty", 
        dataType: 'json', 
        contentType: 'application/json; charset=utf-8', 
        data: JSON.stringify({ dutyNum: dutyNumber, id: id, verb: verb }), 
        success: function (data) { 
         data = $.parseJSON(data.d); 
         if (data.ErrorFound) { 
          showMessage(data.ErrorMessage, 2, true); 
         } 
         else { 
          log('Set Duty: ' + data.StringReturn + ' (' + data.intReturn + ')'); 
         } 
        }, 
        error: function (XMLHttpRequest, textStatus, errorThrown) { 
         alert("updateDuty: " 
          + XMLHttpRequest.responseText); 
        } 
       }); 

       $(this).dialog("close"); 
      }, 
      Cancel: function() { 
       $(this).dialog("close"); 
      } 
     } 

    }); 
    $('#dlgDutyList').dialog('open'); 

FISSO CODICE:

function getLocal(name) { 
var rtn = ""; 
    $.ajax({ 
     type: "POST", 
     async: false, 
     url: "WebServices/FLSAService.asmx/GetLocalVariable", 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     data: JSON.stringify({ name: name }), 
     success: function (data) { 
      rtn = data.d; 
     } 
    }); 
return rtn; 
} 
+0

Che cosa restituisce il servizio Web in merito al posting? Ha il campo in esso? mostra alcuni dati di esempio .. –

+0

'return rtn;' Non è possibile tornare dal callback di successo ajax. Suggerisco di non usare la funzione getLocal o di restituire l'oggetto jqXHR. –

risposta

6

sconfigge lo scopo di AJAX per utilizzarlo in modo sincrono (AJAX sta per Asynchronous JavaScript and XML).

ora è possibile non return un valore dal metodo di successo, ma è possibile memorizzare in una variabile e poi tornare che

function getLocal(name) { 
    var returnValue; 
    $.ajax({ 
     type: "POST", 
     async: false, 
     url: "WebServices/FLSAService.asmx/GetLocalVariable", 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     data: JSON.stringify({ name: name }), 
     success: function (data) { 
      returnValue = data.d; 
     } 
    }); 
    return returnValue; 
} 

Ma il modo corretto sarebbe quella di utilizzare un deferred object

function getLocal(name, resultset) { 
    return $.ajax({ 
     type: "POST", 
     url: "WebServices/FLSAService.asmx/GetLocalVariable", 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     data: JSON.stringify({ name: name }), 
     success: function (data) { 
      resultset[name] = data.d; 
     } 
    }); 
} 

e chiamarlo

"Select": function() { 
    var results = {}; 
    var self = this; 
    $.when(getLocal("VERBID", results), getLocal("VERB", results)).then(function(){ 
     $.ajax({ 
      type: "POST", 
      url: "WebServices/FLSAService.asmx/SetDuty", 
      dataType: 'json', 
      contentType: 'application/json; charset=utf-8', 
      data: JSON.stringify({ 
       dutyNum: dutyNumber, 
       id: results.VERBID, 
       verb: results.VERB 
      }), 
      success: function(data) { 
       data = $.parseJSON(data.d); 
       if (data.ErrorFound) { 
        showMessage(data.ErrorMessage, 2, true); 
       } 
       else { 
        log('Set Duty: ' + data.StringReturn + ' (' + data.intReturn + ')'); 
       } 
      }, 
      error: function(XMLHttpRequest, textStatus, errorThrown) { 
       alert("updateDuty: " + XMLHttpRequest.responseText); 
      } 
     }); 
    }).always(function(){ 
     $(self).dialog("close"); 
    }); 
} 
3

Tutto è dovuto al fatto che la funzione $ .ajax non restituisce alcun valore a causa del suo comportamento asincrono, il mio consiglio è di effettuare il secondo parametro per il metodo getLocal chiamato "callback".

modo corretto è quello di farlo in questo modo:

function getLocal(name, callback) { 
    $.ajax({ 
     type: "POST", 
     async: false, 
     url: "WebServices/FLSAService.asmx/GetLocalVariable", 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     data: JSON.stringify({ name: name }), 
     success: function (data) { 
      var rtn = data.d; 
      callback(rtn); 
     } 
    }); 
} 

Poi, il codice principale deve guardare in quel modo (codice asincrono):

//some code here 
buttons: { 
      "Select": function() { 
       getLocal("VERBID", function(id) { 
        getLocal("VERB", function(verb) { 
         $.ajax({ 
          type: "POST", 
          async: false, 
          url: "WebServices/FLSAService.asmx/SetDuty", 
          dataType: 'json', 
         //some code here 
        }); 
       }); 
//some code here 

Per migliorare questo codice, per fare due chiamate asincrone in una sola volta, è possibile utilizzare l'oggetto jQuery Deferred ed eseguire .resolve(data) su di esso subito dopo che tutte le chiamate ajax hanno ottenuto una risposta adeguata.

+0

Grazie a entrambi i soccorritori. Ho capito che il codice funzionava rapidamente grazie al tuo aiuto. –