簡體   English   中英

未捕獲的TypeError:無法讀取未定義的屬性“長度”

[英]Uncaught TypeError: Cannot read property 'length' of undefined

當我單擊提交按鈕時,如何在嘗試從AJAX調用中獲取數據並將其插入另一個函數時,如何避免以下錯誤?

ajax函數中的console.log調用顯示數據被抓取,我希望然后存儲在json_data中。

然后,目的是使用此數據來更改通過HTML表單提交的字符串。

然后在“click”函數的行返回錯誤:

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>

您沒有正確傳遞變量。 一個快速的解決方案是創建一個這樣的全局變量:

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 
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');

您正在訪問未定義的對象。

解決方案是檢查null或undefined(查看對象是否存在),然后迭代。

“ProjectID”JSON數據格式問題刪除“ProjectID”:此值集合objeckt鍵值

 { * * "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"
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM