将Ajax JQuery选择器保存在数组中

时间:2019-02-12 00:12:34

标签: php jquery arrays json ajax

我对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 :(得分:0)

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 */ }
);

问题是您正在异步调用。

答案 1 :(得分:0)

您同步调用警报,但应异步调用。

一些代码片段可以帮助您了解不同之处:

// $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>