JSON文件未正确加载[重复]

I want to read this JSON file, but the xmlhttp is returning empty.

This is the getJson() function that I am using. I am running this from my local machine.

var getJSON = function(dir) {

    console.log(dir);
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        console.log(xmlhttp);
    }
    xmlhttp.open("GET", dir, true);
    xmlhttp.send();
};
</div>

Alberto,

Since you are using xmlHttp asynchronously, and assuming you want to save the response in a variable, you'll have to modify your getJSON function to accept a callback function and pass the result and/or an error to the callback. So getJSON should be something like this:

var getJSON = function(dir, callback) {

    console.log(dir);
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange=function() {     
        if (xmlhttp.readyState==4) {
            if (xmlhttp.status == 200) {
                console.log('request finished', xmlhttp);
                // pass the response to the callback function
                callback(null, xmlhttp.responseText);

            } else {
                // pass the error to the callback function
                callback(xmlhttp.statusText);
            }
        }
    }

    xmlhttp.open("GET", dir, true);
    xmlhttp.send();
}

To use the function, you'll want something like this:

var myReturnedJSON;

getJSON("http://gomashup.com/json.php?fds=geo/usa/zipcode/state/AL&jsoncallback=", function(error, data){
    if(error) {
        //handle the error
    } else {
        //no error, parse the data
        myReturnedJSON = JSON.parse(data) 
    }

});

Now, the issue with this is that the source returns invalid JSON:

({
    "result":[
    {
        "Longitude" : "-086.466833",
        "Zipcode" : "35004",
        "ZipClass" : "STANDARD",
        "County" : "SAINT CLAIR",
        "City" : "MOODY",
        "State" : "AL",
        "Latitude" : "+33.603543"
    }
]}
)

For this to be valid, it should look like:

{
    "result":[
    {
        "Longitude" : "-086.466833",
        "Zipcode" : "35004",
        "ZipClass" : "STANDARD",
        "County" : "SAINT CLAIR",
        "City" : "MOODY",
        "State" : "AL",
        "Latitude" : "+33.603543"
    }
]}

The difference is in that the valid JSON is not wrapped in parentheses.

So, let's modify the callback function to strip out the first and last characters of the response:

function(error, data){
    if(error) {
        //handle the error
    } else {
        //no error, parse the data
        myReturnedJSON = JSON.parse( data.substr(1, data.length - 2) );
    }

}

I hope that helps! - Oscar