是否有可能知道在OOP方法中何时完成了ajax调用

时间:2018-01-17 12:00:23

标签: javascript jquery ajax oop

很抱歉这个令人困惑的标题。我无法用更好的方式描述它。

所以这就是我想要找到的东西。我们说

function myClass()
{
   $.ajax({
      type:'get',
      url:'some/path/',
      success:function(response)
      {
         // call has been compeleted, set some flag here
      }
   });

   return this;
}

var obj = new myClass();
jQuery('body').append('<div id="overlay"></div>'); // so now the user will know he has to wait for some operation to be completed...    

// now determine on this line whether the Ajax call is still in progress
while(<ajax call still in progress>)
{
   // i do not need to do anything here since the overlay is already there in place
}

// now this is where I want to remove the overlay
jQuery('#overlay').remove();

更新

基本上,我在进行ajax调用时显示加载覆盖,一旦完成,我想删除该覆盖。 我知道我可以在类本身内编写代码,但我希望控制在类外添加/删除叠加层。

3 个答案:

答案 0 :(得分:2)

您应该使用此类请求的承诺性质。所以请参考什么 then会在您创建的对象的属性中返回。

然后,您可以在该属性上使用function myClass(path) { this.request = $.ajax({ // ^^^^^^^^^^^^ type: 'get', url: path, }); } var obj = new myClass('https://httpstat.us/200?sleep=1000'); jQuery('body').append('<div id="overlay"></div>'); obj.request.then(function(response) { console.log('done'); jQuery('#overlay').remove(); });方法来了解所有操作的完成时间。

以下代码调用测试服务器,在请求待处理(1秒)时显示银色覆盖:

#overlay {
    position: absolute;
    width: 100%;
    height: 100%;
    background: silver;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Option Explicit

Public Namepatch3 As String

Sub Figures()


Dim Filt As String
Dim IndexFiltre As Integer, NomFichier As Variant, Titre As String
Dim o As Integer, p As Integer
Dim Msg As String
Dim ConsoPDC As Workbook
Dim Fichier As String, fichier1 As String, chaine As String
Dim feuille As Variant
Dim Reponse As Integer
Dim Config As Integer
Dim nomClasseur As Variant
Dim vclasseur As Workbook
Dim resum As Workbook
Dim wkb As Workbook
Dim ws As Worksheet

Dim n
    With Worksheets("Dest")
        n = .Range("L" & .Rows.Count).End(xlUp).Row + 1
    End With

Set wkb = ActiveWorkbook

Namepatch3 = ThisWorkbook.Name

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'   File filters list
Filt = "txt files (*.txt),*.txt," & _
        "Lotus files (*.prn),*.prn," & _
        "Comma separated files (*.csv),*.csv," & _
        "ASCII files (*.asc),*.asc," & _
        "All files (*.*),*.*"
'   display *.* by default
IndexFiltre = 5
'   DialogBox
Titre = "Sélectionner les fichiers à traiter"
'   Get file name
NomFichier = Application.GetOpenFilename _
    (fileFilter:=Filt, _
     FilterIndex:=IndexFiltre, _
     Title:=Titre, _
     MultiSelect:=True)
'   Quit if the dialogbox is cancelled
If Not IsArray(NomFichier) Then
    MsgBox "No files were selected!"
    Application.StatusBar = False
    GoTo TheEnd
End If
'   display the entire path + file name
Config = vbYesNo + vbInformation + vbDefaultButton2
For o = LBound(NomFichier) To UBound(NomFichier)
    Msg = Msg & NomFichier(o)
Next o
Reponse = MsgBox("Please find below your file :" & vbCrLf & Msg & vbCrLf, Config, "MAJ resum")
If Reponse = vbNo Then
  GoTo TheEnd
End If


  '   MsgBox (Msg) ' Source file
   ' Test to check if the file has already been opened

   ' If yes => close file or use the opened file ? 
    Workbooks.Open Filename:=Msg


'------------------------------------------------------------------------------------------------------
Only select file name instead of whole path
fichier1 = Right(Msg, Len(Msg) - InStrRev(Msg, "\", -1, 1))
Fichier = Left(fichier1, InStr(fichier1, ".xls") - 1)

'Import process
'------------------------------------------------------------------------------------------------------

Dim i As Integer
Dim j As Integer
Dim K As Integer
Dim l  As Integer

Dim debutcols As Integer ' Year in number ?
Dim fincols As Integer ' Year in number ?
Dim debutas As Integer ' Column N° first year
Dim finas As Integer ' Column N° last year
Dim debutcold As Integer
Dim fincold As Integer
Dim debutad As Integer
Dim finad As Integer
Dim rowmaxwallets As Integer
Dim rowmaxwalletd As Integer
Dim c As Object
Dim therow As Integer
Dim Nlp As String
Dim Vcol(30) As Variant ' data paste year
Dim cpt As Integer


Windows(fichier1).Activate
Worksheets("DataBase").Select

debutcols = CInt(Worksheets("DataBase").Cells(1, 22))  ' (col V)  XXXX
debutas = 22
fincols = 0
fincold = 0
finas = 0
debutad = 0
finad = 0

' End column in source file
i = 0
For i = 1 To 30
   If Len(Worksheets("DataBase").Cells(1, i + 22)) = 4 Then
     ' If a year is found
     Else
     ' Plus 1 column
     i = i - 1
     finas = (22 + i)
     fincols = CInt(Worksheets("DataBase").Cells(1, i + 22))
     GoTo sortie
   End If
Next

sortie:
   Columns(ConvertCol(debutas) & ":" & ConvertCol(finas)).Select

   Windows(Namepatch3).Activate
   Worksheets("Dest").Select
   i = 0

   For i = 1 To 70
   If Worksheets("Dest").Cells(1, i) = debutcols Then
     debutcold = i
     debutad = i

     GoTo sortie2
     End If
   Next i

sortie2:
     finad = debutad + (finas - debutas)

   Windows(fichier1).Activate
   Sheets("DataBase").Select
   rowmaxwallets = CInt(Worksheets("DataBase").Cells(Columns(1).Cells.Count, 1).End(xlUp).Row)

   Windows(Namepatch3).Activate
   Worksheets("LP").Select

   rowmaxwalletd = CInt(Worksheets("LP").Cells(Columns(1).Cells.Count, 1).End(xlUp).Row)
   i = 0
   cpt = 1

   Application.ScreenUpdating = True
   Application.Calculation = xlCalculationManual

   For i = 1 To rowmaxwalletd ' loop on all lines in source file


     Windows(Namepatch3).Activate
     Sheets("LP").Select


         'Read source file
     For l = 1 To rowmaxwallets
        ' dynamically copy figures
        Windows(fichier1).Activate
        Sheets("DataBase").Select
                   For j = 0 To (finas - debutas)
             Vcol(j) = Worksheets("Database").Cells(1822 + l, debutas + j)
           Next j
                     Windows(Namepatch3).Activate
           Worksheets("Dest").Select

          ' Paste figures
           For j = 0 To (finas - debutas)
             Worksheets("Dest").Cells(n, debutad + j) = Vcol(j)
           Next j
           n = n + 1


     Next l
   Next i
fin:
   Application.StatusBar = False
   Application.ScreenUpdating = True
   Application.Calculation = xlCalculationAutomatic
   Worksheets("Dest").Select
   Range("A3").Select
   MsgBox ("Import done")

   'Set resource free

    Set wkb = Nothing

    Windows(fichier1).Activate
        ActiveWorkbook.Close

TheEnd:

End Sub

任何使这种代码同步的尝试都是不好的做法。您需要接受Ajax调用的异步特性,并使用回调系统,如promises中提供的那样。

答案 1 :(得分:1)

我就是这样做的:

/* The constructor. */
function myClass(successCallback) {
  $.ajax({
    context: this,
    type: "get",
    url: "some/path/",
    success: function(response) {
      this.inProgress = false;
      successCallback.call(this);
    }
  });

  this.inProgress = true;
}

/* Create a new class and add an overlay to the body. */
var obj = new myClass(removeOverlay);
jQuery('body').append('<div id="overlay"></div>');

/* The function that removes the overlay. */
function removeOverlay () {
  if (!this.inProgress) jQuery('#overlay').remove();
}

答案 2 :(得分:1)

您可以将回调作为参数传递给对象构造函数:

function myClass(onStart, onStop) {
    $.ajax({
        type:'get',
        url:'some/path',
        data: {
            action: 'test'
        },
        beforeSend: function() {
            if (onStart && typeof onStart == 'function') {
                onStart();
            }
        },
        success: function(response) {
            //do something
        },
        complete: function() {
            if (onStop && typeof onStop == 'function') {
                onStop();
            }
        }
    });
}

var onStart = function () {
    console.log('Started');
}
var onStop = function () {
    console.log('Stopped');
}

var obj = new myClass(onStart, onStop);