2016-02-05 39 views
1

伊夫包括我下面的腳本,在那裏我試圖把一個JSON文件到使用Ajax回調函數一個網站的最末端。當我檢查頁面時,我看到JSON文件格式不正確,我似乎無法找到答案。該網頁還顯示JSON文件是「未定義的」。建議感激!GeoJSON的「不規範」,在控制檯消息,並出現未定義

function debugCallback(response){ 

    var mydata; 

    $("#mydiv").append('GeoJSON data: ' + JSON.stringify(mydata)); 
}; 


function debugAjax(){ 

    var mydata; 

    $.ajax("data/MegaCities.GeoJSON", { 
     dataType: "json", 
     success: function(response){ 
      //mydata = response; 
      debugCallback(mydata); 
     } 
    }); 

    $("#mydiv").append('<br>GeoJSON data:<br>' + JSON.stringify(mydata)); 
}; 

//$("#mydiv").append('GeoJSON data: ' + JSON.stringify(mydata)); 
if(typeof mydata === 'undefined') { 
    console.log("undefined data") 
} else { 
    console.log("not undefined") 
} 
$(document).ready(debugAjax()); 
+0

$ .getJSON()試試這個和http://api.jquery.com/jquery.getjson/ –

回答

0

避免定義多種功能,並嘗試只使用這樣的:

$(document).ready(function(){ 
    $.ajax("data/MegaCities.GeoJSON", { 
     dataType: "json", 
     success: function(response){ 
      $("#mydiv").append('<br>GeoJSON data:<br>' + JSON.stringify(response)); 
     } 
    }); 
}); 

注意,之後我們得到的響應/來自AJAX調用數據,我們進行格式化爲JSON。

0

您正在使用var mydata並且未定義它,因此當您將它作爲值傳遞時它正在顯示正確的消息undefined

你或許應該修改這樣的代碼。

$(document).ready(function(){ 
    $.ajax({ 
    url: "data/MegaCities.GeoJSON", 
    method: 'GET' , 
    aysnc: false, 
    success: function(response){ 
     $("#mydiv").append('GeoJSON data:' +response); 
    } 
    }); 
});