将JSON数据写入变量

时间:2015-11-18 21:34:56

标签: javascript json weather

我正在开展一个项目,我需要将天气数据写入变量。 (URL = http://api.openweathermap.org/data/2.5/weather?zip=96950,us&appid=2de143494c0b295cca9337e1e96b00e0)如何获得该区域的温度?

1 个答案:

答案 0 :(得分:1)

在以下代码中,<url>代表您的http://api.openweathermap.org/data/2.5/weather?zip=96950,us&appid=2de143494c0b295cca9337e1e96b00e0字符串格式的网址。

使用此代码使用带有Vanilla JS(无框架)的URL中的数据JSON:

/**
 * The function to reach JSON data from an `<url>`
 * function getJSON
 * @param {string}   url  - The string url we want to reach to obtain an object JSON from an url.
 * @param {function} next - What you want do after obtain the JSON data. See after.
 */
function getJSON(url, next) {

    // Create an object to perform an AJAX call.
    var request = new XMLHttpRequest();
    // Declare what method you will use, to what url, and if the rest of code will wait the response (false) or if this call will be async (true).
    request.open("GET", url, true);
    // Perform the request.
    request.send();

    // What we want to do if the url is correctly reached.
    request.addEventListener("load", function () {
        // The data are invalid if this condition of status is respected.
        if (request.status < 200 && request.status >= 400) {
            // return is used to stop the execution of script and return the effective error.
            return next(new Error("We reached our target server, but it returned an error."));
        }

        /**
         * All is fine. Use the next() callback.
         * @callback next
         * @memberOf getJSON~
         * @param {null|Object}      err  - null if no error occur, a `new Error()` object if an error occured.
         * @param {object|undefined} data - Only in case of success, the data we want obtain from url to JSON format.
         */
        next(null, JSON.parse(request.responseText));
    });

    // What we want to do if an error occured.
    request.addEventListener("error", function () {
        // An error is occured, send this error.
        next(new Error("There was a connection error of some sort."));
    });
}

/* Use the previous declared function with real string url in place of `<url>` */
getJSON(<url>, function (err, data) {
    // In case of errror...
    if (err) {
      // ...We will return a message for example
      return err;
    }

    // Or in success case, use data !
    data;
});

或以其他方式here a JavaScript explaination for this function使用XMLHttpRequest()

与jQuery相同的代码:

function getJSON(url, next) {
    $.getJSON(url, function (data) {
      next(null, data);
    }).error(function () {
      next(new Error("There was a connection error of some sort."));
    });
}
getJSON(<url>, function (err, data) {
    if (err) {
      return err;
    }
    data;
});

或者只使用$.getJSON()here API explaination for this function