简体   繁体   English

页面加载时未定义的ajax响应

[英]Undefined ajax response when page load

I have a script, below, and when the page loads I get an error message: Cannot read property 'length' of undefined , so I researched the error and found that the AJAX request wasn't executed. 我在下面有一个脚本,当页面加载时,我收到一条错误消息: Cannot read property 'length' of undefined ,因此我研究了该错误,发现未执行AJAX请求。 If I execute the same code in the browser console, the script works fine. 如果我在浏览器控制台中执行相同的代码,则脚本可以正常工作。 What's wrong with my code? 我的代码有什么问题?

<script>

function getCitiesList() {
  var country_id = '189';
  return $.ajax({
    type: 'get',//тип запроса: get,post либо head
    url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
  });
}

function getCitiesList2() {
  var bla = getCitiesList();
  console.log(bla['responseJSON']);
  var i = 0;
  var data = [];
  while (i < bla['responseJSON'].length) {
    data[i] = {};
    data[i]['id'] = bla['responseJSON'][i]['id'];
    data[i]['text'] = bla['responseJSON'][i]['title'];
    i++;
  }
  console.log(data);
}


$('#city').select2({
  data: getCitiesList2(),
  width: "100%"
});

</script>

Since JavaScript is asynchronous language, it just keeps running and doesn't wait for AJAX to return result. 由于JavaScript是异步语言,因此它可以继续运行,而无需等待AJAX​​返回结果。

In your code, the first line of getCitiesList2 function assigns the return value of an AJAX call. 在您的代码中, getCitiesList2函数的第一行分配AJAX调用的返回值。 The AJAX returns later , and var bla doesn't yet have the response. AJAX 稍后返回,并且var bla尚未响应。 To solve this, you can pass a callback to your AJAX function getCitiesList and execute it on AJAX success. 为了解决这个问题,您可以将回调传递给AJAX函数getCitiesList ,并在AJAX成功时执行它。

function getCitiesList(callback) {
  var country_id = '189';
  $.ajax({
    type: 'get',//тип запроса: get,post либо head
    url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
    success: function(result) {
      callback(result);
    }
  });
}

function getCitiesList2() {
  getCitiesList(function(result) {
    var i = 0;
    var data = [];
    while (i < result['responseJSON'].length) {
      data[i] = {};
      data[i]['id'] = result['responseJSON'][i]['id'];
      data[i]['text'] = result['responseJSON'][i]['title'];
      i++;
    }
  });
}

The problem is that console.log(bla['responseJSON']); 问题是console.log(bla['responseJSON']); in getCitiesList2 is executed before the ajax response is received. 在接收到ajax响应之前,将执行getCitiesList2中的。 And after var bla = getCitiesList(); var bla = getCitiesList(); assignment, bla basically holds a deferred object . 分配时, bla基本上保留了一个延迟对象 All you need to do is to assign a callback function that is going to be executed once the ajax call returns. 您需要做的就是分配一个回调函数,该函数将在ajax调用返回时执行。

<script>

function getCitiesList() {
  var country_id = '189';
  return $.ajax({
    type: 'get',//тип запроса: get,post либо head
    url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
  }).done(function(data){         
     $('#city').select2({
       data: processCitiesResponse(data),
       width: "100%"
     });
  });
}

function processCitiesResponse(data)
{
     console.log(data);
     var i = 0;
     var options = [];
     while (i < data.responseJSON.length) {
        options[i] = {};
        options[i].id = data.responseJSON[i].id;
        options[i].text = data.responseJSON[i].title;
        i++;
     }
     console.log(options );
}


</script>

first and second answer doesn't help, the same problem. 第一个和第二个答案无济于事,同样的问题。

This work: 这项工作:

<script>
                              var AUTH_TOKEN = $('meta[name=csrf-token]').attr('content');
                              function Blabla(){
                                var country_id = '189';
                                $.ajax({
                                  type: 'get',
                                  url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
                                  success: function(bla){
                                    var i = 0;
                                    var data = [];
                                    while (i < bla.length) {
                                      data[i] = {};
                                      data[i]['id'] = bla[i]['id'];
                                      data[i]['text'] = bla[i]['title'];
                                      i++;
                                    }
                                    $('#city').select2({
                                      data: data,
                                      width: "100%"
                                    });
                                  }
                                });
                              }
                              Blabla();
                          </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM