Сохранить селектор Ajax JQuery в массиве - PullRequest
0 голосов
/ 12 февраля 2019

Я очень плохо знаком с Ajax, и мне нужна помощь для сохранения данных из запроса Ajax в массив.Я посмотрел ответы здесь на форуме, но я не смог решить мою проблему. Ответ Ajax входит в $('#responseField').val(format(output.response)), и я хочу сохранить «output.response» в массив, который можно использовать внеAjax.Я пытался объявить переменную вне Ajax и вызвать ее позже, но безуспешно.Я использую $json_arr, который должен получить данные.Как мне получить данные из Ajax и сохранить их в переменной, которая будет использоваться за пределами Ajax?Эта переменная будет массивом, к которому я могу получить доступ к индексам.

function sendRequest(postData, hasFile) {

  function format(resp) {
    try {
      var json = JSON.parse(resp);
      return JSON.stringify(json, null, '\t');
    } catch(e) {
      return resp;
    }
  }

  var value; // grade item
  $.ajax({
          type: 'post',
          url: "doRequest.php",
          data: postData,
          success: function(data) { //data= retArr

            var output = {};

            if(data == '') {
              output.response = 'Success!';
            } else {
              try {
                output = jQuery.parseJSON(data);


              } catch(e) {
                output = "Unexpected non-JSON response from the server: " + data;
              }
            }
            $('#statusField').val(output.statusCode);
            $('#responseField').val(format(output.response));

            $("#responseField").removeClass('hidden');
            data = $.parseJSON(output.response)
            $json_arr=$('#responseField').val(format(output.response));
          },
          error: function(jqXHR, textStatus, errorThrown) {
            $('#errorField1').removeClass('hidden');
            $("#errorField2").innerHTML = jqXHR.responseText;
          }

  });

}

window.alert($json_arr);

Ответы [ 2 ]

0 голосов
/ 12 февраля 2019

Вы вызываете оповещение синхронно, но оно должно вызываться асинхронно.

Небольшой фрагмент, который поможет вам увидеть разницу:

// $json_arr initialized with a string, to make it easier to see the difference
var $json_arr = 'Hello World!';

function sendRequest() {

  $.ajax({
    // dummy REST API endpoint
    url: "https://reqres.in/api/users",
    type: "POST",
    data: {
        name: "Alert from AJAX success",
        movies: ["I Love You Man", "Role Models"]
    },
    success: function(response){
        console.log(response);
        $json_arr = response.name;
        // this window.alert will appear second
        window.alert($json_arr);
    }
  });

}
sendRequest();
// this window.alert will appear first
window.alert($json_arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
0 голосов
/ 12 февраля 2019
let promise = new Promise(function(resolve, reject) {
  $.ajax({
          type: 'post',
          url: "doRequest.php",
          data: postData,
          success: function(data) { //data= retArr

            var output = {};

            if(data == '') {
              output.response = 'Success!';
            } else {
              try {
                output = jQuery.parseJSON(data);


              } catch(e) {
                output = "Unexpected non-JSON response from the server: " + data;
              }
            }
            $('#statusField').val(output.statusCode);
            $('#responseField').val(format(output.response));

            $("#responseField").removeClass('hidden');
            data = $.parseJSON(output.response)
            resolve(format(output.response));
          },
          error: function(jqXHR, textStatus, errorThrown) {
            $('#errorField1').removeClass('hidden');
            $("#errorField2").innerHTML = jqXHR.responseText;
          }

  });
});
promise.then(
  function(result) { /* you can alert a successful result here */ },
  function(error) { /* handle an error */ }
);

Проблема в том, что вы звоните асинхронно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...