S
S
semki0962016-03-21 11:22:56
JavaScript
semki096, 2016-03-21 11:22:56

Ajax - using done or success?

I can not understand. Let's assume this situation

$.ajax({
                            url: "node"
                            }).done(function(data){
$.ajax({
                            url: "node2"
                            }).done(function(data){
$.ajax({
                            url: "node3"
...

In the third function, can't we use the data of the first one? And what is the correct way to build such things? C success ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shcherbakov, 2016-03-21
@semki096

In the third function, can't we use the data of the first one?

You can if you declare variables in the global, for example a = 0;
But I want to note that the logic itself is lame, why hammer three requests (in case of a successful response)? Isn't it easier to execute one request, and provide the server with the fulfillment of the condition?
A small example of code that I sometimes use:
// где-то в одной далекой функции или событии собираю данные для запроса
    var Id = '127';
    var Name = 'Test';

    var data = JSON.stringify({
      Type:'Save',
      Data: {
        Id:Id,
        Name:Name
      }
    }); // собираю JSON который будет отправлен, соотвественно можно отослать и не JSON

    var s = {
      type:'POST',
      url:'conn.php',
      data:data,
      dataType:'json',
      parent: 'thisFunction'
    }; // подготавливаю данные для функции отправки

    SendData(s); // вызываю саму функцию отправки


/////////////////////////////


  function SendData(s) {
    $.ajax({
      type: s.type,
      url: s.url,
      data: s.data,
      cache: false,
      dataType: s.dataType,
      timeout: 15000,
      success: function(r) {
        SendSuccess(r, s); // успех, шлем полученный ответ
      },
      error: function(jqXHR, textStatus, errorThrown) {
        SendError(s); // ошибка, в SendError можно так же передать состояние ошибки, например SendError(s, textStatus)
      }
    });
  }

  function SendSuccess(r, s) {
    if (s.parent == 'thisFunction') {
      // вызываем необходимую функцию или событие, можем передать ответ r
    }
  }

  function SendError(s) {
    if (s.parent == 'thisFunction') {
      // можем передать функции состояние ошибки, если логика работы вызвавшей или принимающей функции будет ожидать завершения какого-либо действия
    }
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question