JQuery和Ajax:无法读取未定义的属性“长度”

时间:2013-01-07 16:26:05

标签: jquery ajax

我试图通过在URL和AJAX中使用变量来显示JSON来从网站获取特定请求。似乎一切正常,但有一个错误“TypeError:无法读取未定义的属性'长度'”。调试器指向JQuery文件和我脚本中的行($ .ajax.success)。

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  alert('Query Variable ' + variable + ' not found');
}

$(document).ready(function () {

  var output = $('#news');
  var postid = getQueryVariable('id');

  $.ajax({
    url: 'http://www.domain.pro/api/get_post/?post_id=' + postid + '&post_type=news',
    async: false,
    callback: 'callback',
    crossDomain: true,
    contentType: 'application/json; charset=utf-8',
    type: 'POST',
    dataType: 'jsonp',
    timeout: 5000,
    success: function (data, status) {
       $.each(data.posts, function (i, item) {
        var news = '<div>' + item.title + '</div><div>' + item.content + '</div><hr/>';

        output.append(news);


      });
    },
    error: function () {
      output.text('There was an error loading the data.');
    }
  });
})
你可以帮我解决这个问题吗?真的很感激你的踌躇。

2 个答案:

答案 0 :(得分:5)

您应该在对数据执行操作之前验证数据:

<强>已更新

 $.ajax({
            url: 'http://www.domain.pro/api/get_post/?post_id=' + postid + '&post_type=news',
            async: false,
            callback: 'callback',
            crossDomain: true,
            contentType: 'application/json; charset=utf-8',
            type: 'POST',
            dataType: 'jsonp',
            timeout: 5000,
            success: function (data, status) {
               if(data != undefined && data.post != undefined){
                 $('#news').append('<div>' + data.post.title + '</div><div>' + data.post.content + '</div><hr/>');
                }
            },
            error: function () {
              output.html('<h1 class="error">There was an error loading the data.</h2>');
            }
          });

答案 1 :(得分:1)

您在data.post上应用$ .each,如果您的数据为空,则可能未定义。 $ .each期望和数组或集合,这就是你得到长度错误的原因。由于您的数据为空,因此data.post将是未定义的。你可以在应用$ .each之前检查

if(typeof data == "object" && data.post)
    //Your code here.

只要您期望来自ajax的某些数据,就应该应用此检查。