未捕获的TypeError:无法读取未定义的属性“长度”

时间:2013-11-12 13:15:22

标签: javascript jquery json scope

当我点击提交按钮时,如何在尝试从AJAX调用中获取数据并将其插入另一个函数时,如何避免以下错误?

ajax函数中的console.log调用显示数据被抓取,我希望然后存储在json_data中。

目的是使用此数据来更改通过HTML表单提交的字符串。

然后在“点击”功能的行中返回错误:

console.log(json_data.length);

<title>Test Form</title>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    #results_box {
        border: red 5px solid;
                }

    #place {
        border: #cccccc 1px solid;

    }           
</style>
<script type="text/javascript">
$(document).ready(function() {
    var json_source = "https://spreadsheets.google.com/feeds/list/0ApL1zT2P00q5dG1wOUMzSlNVV3VRV2pwQ2Fnbmt3M0E/od7/public/basic?alt=json";
    var string_data ="";
    var json_data = $.ajax({
        dataType: 'jsonp',
        url: json_source,
        success: function(data){
            var data_obj = [];
            for (i=0; i<data.feed.entry.length; i++){
                var el = {'key': data.feed.entry[i].title['$t'], 'value': '<p><a href="'+data.feed.entry[i].content['$t']+'>'+data.feed.entry[i].title['$t']+'</a></p>'};
                data_obj.push(el)};

            console.log("data grabbed");    

            return data_obj;

        },      

        error: function(jqXHR, textStatus, errorThrown){ 
                        $('#results_box').html('<h2>Something went wrong!</h2><p><b>' + textStatus  + '</b> ' + errorThrown  + '</p>');
        }
    }); 

    $(':submit').click(function(event, json_data){
        event.preventDefault();
        console.log(json_data.length);

        //function
        if ($('#place').val() !=''){
            var copy_string = $('#place').val();
            var converted_string = copy_string;
            for (i=0; i<json_data.length; i++){
                //console_log(data.feed.entry[i].title['$t']);
                converted_string = converted_string.replace(json_data.feed.entry[i].title['$t'], 
                    '<a href="'+json_data.feed.entry[i].content['$t']+'>'+json_data.feed.entry[i].title['$t']+'</a>');
            }  
            $('#results_box').text(converted_string).html();
        }
    });

});//document ready end 

</script>
</head>

<body>
    <div id="wrapper">
    <div id="query_box" class="panel">  
        <form id="form_submit"><h4>Copy to process:</h4>
          <textarea id="place"></textarea>
          <input type="submit" value="Go" />

        </form>
    </div>
   <div id="results_box" >Results will appear here</div>  
</div>

 

4 个答案:

答案 0 :(得分:11)

您没有正确传递变量。一个快速的解决方案是创建一个这样的全局变量:

var global_json_data;
$(document).ready(function() {
    var json_source = "https://spreadsheets.google.com/feeds/list/0ApL1zT2P00q5dG1wOUMzSlNVV3VRV2pwQ2Fnbmt3M0E/od7/public/basic?alt=json";
    var string_data ="";
    var json_data = $.ajax({
        dataType: 'json', // Return JSON
        url: json_source,
        success: function(data){
            var data_obj = [];
            for (i=0; i<data.feed.entry.length; i++){
                var el = {'key': data.feed.entry[i].title['$t'], 'value': '<p><a href="'+data.feed.entry[i].content['$t']+'>'+data.feed.entry[i].title['$t']+'</a></p>'};
                data_obj.push(el)};

            console.log("data grabbed");  
            global_json_data =   data_obj;

            return data_obj;


        },      

        error: function(jqXHR, textStatus, errorThrown){ 
                        $('#results_box').html('<h2>Something went wrong!</h2><p><b>' + textStatus  + '</b> ' + errorThrown  + '</p>');
        }
    }); 

    $(':submit').click(function(event){
        var json_data = global_json_data;
        event.preventDefault();
        console.log(json_data.length);

        //function
        if ($('#place').val() !=''){
            var copy_string = $('#place').val();
            var converted_string = copy_string;
            for (i=0; i<json_data.length; i++){
                //console_log(data.feed.entry[i].title['$t']);
                converted_string = converted_string.replace(json_data.feed.entry[i].title['$t'], 
                    '<a href="'+json_data.feed.entry[i].content['$t']+'>'+json_data.feed.entry[i].title['$t']+'</a>');
            }  
            $('#results_box').text(converted_string).html();
        }
    });

});//document ready end 

答案 1 :(得分:5)

console.log(typeof json_data !== 'undefined'
    ? json_data.length : 'There is no spoon.');

......或更简单......

console.log(json_data ? json_data.length : 'json_data is null or undefined');

答案 2 :(得分:2)

您正在访问未定义的对象。

解决方案是检查是否为null或未定义(以查看对象是否存在),然后进行迭代。

答案 3 :(得分:1)

  

“ProjectID”JSON数据格式问题删除“ProjectID”:此值   收集对象关键值

 { * * "ProjectID" * * : {
            "name": "ProjectID",
            "value": "16,36,8,7",
            "group": "Genel",
            "editor": {
                "type": "combobox",
                "options": {
                    "url": "..\/jsonEntityVarServices\/?id=6&task=7",
                    "valueField": "value",
                    "textField": "text",
                    "multiple": "true"
                }
            },
            "id": "14",
            "entityVarID": "16",
            "EVarMemID": "47"
        }
    }
相关问题