如何使用javascript从url加载json?

时间:2014-02-16 17:31:22

标签: javascript

我是javascript的新手,应该很容易解决,但我现在已经迷失了。

我有一个网址:http:getall.json 使用JavaScript(不是JQuery或php。只是JavaScript),我想读取这个JSON字符串并解析它。就是这样。

3 个答案:

答案 0 :(得分:1)

访问您的网址无效,您应该显示JSON结果。在javascript中使用AJAX请求获取JSON对象,您可以执行以下操作:

request = new XMLHttpRequest;
request.open('GET', 'http://v-apps-campaign.com/dunkindonuts/main/get_allStore', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400){
    // Success!
    data = JSON.parse(request.responseText);
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

您的结果将在data变量中。

答案 1 :(得分:1)

JSONP 来电:

function getJSONP(url, callback) {
    var script = document.createElement('script');
    var callbackName = "jsonpcallback_" + new Date().getTime();
    window[callbackName] = function (json) {
        callback(json);
    };
    script.src = url + (url.indexOf("?") > -1 ? "&" : "?") + 'callback=' + callbackName;

    document.getElementsByTagName('head')[0].appendChild(script);
}
getJSONP("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function(jsonObject){
    //jsonObject is what you want
});

常规ajax ajax 致电:

function getXHR() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    }
    try {
        return new ActiveXObject('MSXML2.XMLHTTP.6.0');
    } catch (e) {
        try {
            // The fallback.
            return new ActiveXObject('MSXML2.XMLHTTP.3.0');
        } catch (e) {
            throw new Error("This browser does not support XMLHttpRequest.");
        }
    }
}

function getJSON(url, callback) {
    req = getXHR();
    req.open("GET", url);
    req.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var jsonObject = null,
                status;
            try {
                jsonObject = JSON.parse(req.responseText);
                status = "success";
            } catch (e) {
                status = "Invalid JSON string[" + e + "]";
            }
            callback(jsonObject, status, this);
        }
    };
    req.onerror = function () {
        callback(null, "error", null);
    };
    req.send(null);
}
getJSON("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function (jsonObject, status, xhr) {
    //jsonObject is what you want
});

我使用您的网址测试了这些内容,看起来您应该通过 jsonp 调用来获取数据,因为通过常规的ajax调用它会返回:

No 'Access-Control-Allow-Origin' header is present on the requested resource

jsonp 它获取数据,但数据不是有效的json,看来你的服务器端有一些 php错误

A PHP Error was encountered

...

答案 2 :(得分:1)

在您的HTML中包括json文件和一个js代码作为模块

<script src="/locales/tshared.js"  type="module"  ></script>
<script src="/scripts/shared.js" type="module"  ></script>

共享的文件内容

export const loc = '{"en": { "key1": "Welcome" },"pt": {"key1": "Benvindo"} }'
file content of shared
import {loc} from "./../../locales/tshared.js";
var locale = null;
locale = JSON.parse(loc) ;

根据需要调整路径和名称,请随意使用区域设置。