未捕获的TypeError:不能使用'in'运算符来搜索(jQuery)中的'0'

时间:2014-08-04 16:53:19

标签: javascript jquery

我觉得这与AJAX调用有关。不确定发生了什么。从技术上讲,错误是在第584行的jQuery文件中抛出的,它定义了isArraylike(obj)函数。

jQuery(document).ready(function(){
  var width_of_grams = $(window).width();
  var new_pic_height = (width_of_grams /7);
  $("img.gram_photo").css('height', (width_of_grams) / 7);
  $("#instafeed").css('height', 2*new_pic_height);

  $(window).resize(function() {  
    var width_of_grams = $(window).width();
    var new_pic_height = (width_of_grams /7);
    $("img.gram_photo").css('height', (width_of_grams) / 7);
    $("#instafeed").css('height', 2*new_pic_height);
  });


  $("#school_application_fls_center_name").change(function(){
    var center_name = document.getElementById("school_application_fls_center_name").value;
    var formdata = {center: center_name}; 
    $.ajax({
        url: "/application/get_programs_for_center",
        type: "POST",
        data: formdata,
        success: function(response){
          var options = $("#school_application_program_name"); 
          console.log(response);
          $.each(response, function(i,item) {
            options.append($("<option />").val(response[i].id).text(response[i].name)); 
          });
        }
    });
  });
});

以下是抛出错误的jQuery库代码:

function isArraylike( obj ) {
  var length = obj.length,
    type = jQuery.type( obj );

    if ( type === "function" || jQuery.isWindow( obj ) ) {
        return false;
    } 

    if ( obj.nodeType === 1 && length ) {
        return true;
    }

    return type === "array" || length === 0 ||
        typeof length === "number" && length > 0 && ( length - 1 ) in obj; //THIS LINE THROWS ERROR
}

N.B。当我删除AJAX请求成功部分中的所有回调函数时,    然后放一个console.log来确认我正在成功打印回调     我的日志消息并没有抛出错误。

2 个答案:

答案 0 :(得分:8)

我认为你的回复是一个JSON字符串。尝试传递

dataType: 'json'

在您的ajax参数中,或使用以下命令显式反序列化:

response = JSON.parse(response)
在你打电话给$ .each之前

浏览器会话:

// Create some JSON:
json = '["foo", "bar"]'
"["foo", "bar"]"

// Try parsing it, to check it is indeed JSON:
JSON.parse(json)
["foo", "bar"]

// But without parsing it, call $.each on it - we get your error:
$.each(json, function(idx, thing) {console.log(thing)})
TypeError: Cannot use 'in' operator to search for '13' in ["foo", "bar"]

// Now try $.each and JSON.parse - success!
$.each(JSON.parse(json), function(idx, thing) {console.log(thing)})
foo VM410:2
bar VM410:2
["foo", "bar"]

答案 1 :(得分:0)

因此,当我收到此错误时,我实际上并没有正确地在服务器端提供响应。在我的Rails控制器中,我有:

def controller_method_to_handle_post
  render nothing :true
end

所以我基本上得到了来自服务器的null响应。那么当我去解析时 使用$.each的响应我遇到了jQuery错误,它说它不能遍历我传递它的这个空对象。