Javascript 如何使用ajax从文件加载JSON对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14388452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:37:03  来源:igfitidea点击:

How do I load a JSON object from a file with ajax?

javascriptajaxjson

提问by rubo77

I am using JSON to transfer data.

我正在使用 JSON 传输数据。

What do I need in my HTML page to read a file with Ajax that only includes one JSON object into my script?

我的 HTML 页面需要什么才能使用 Ajax 读取仅包含一个 JSON 对象的文件到我的脚本中?

Do I need jQuery too, or is it possible to load that JSON file with Ajax?

我是否也需要 jQuery,或者是否可以使用 Ajax 加载该 JSON 文件?

Is it different on different browsers?

在不同的浏览器上有区别吗?

回答by Denys Séguret

You don't need any library, everything is available in vanilla javascript to fetch a json file and parse it :

你不需要任何库,一切都可以在 vanilla javascript 中获取一个 json 文件并解析它:

function fetchJSONFile(path, callback) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                var data = JSON.parse(httpRequest.responseText);
                if (callback) callback(data);
            }
        }
    };
    httpRequest.open('GET', path);
    httpRequest.send(); 
}

// this requests the file and executes a callback with the parsed result once
//   it is available
fetchJSONFile('pathToFile.json', function(data){
    // do something with your data
    console.log(data);
});

回答by Niet the Dark Absol

The most efficient way is to use plain JavaScript:

最有效的方法是使用纯 JavaScript:

var a = new XMLHttpRequest();
a.open("GET","your_json_file",true);
a.onreadystatechange = function() {
  if( this.readyState == 4) {
    if( this.status == 200) {
      var json = window.JSON ? JSON.parse(this.reponseText) : eval("("+this.responseText+")");
      // do something with json
    }
    else alert("HTTP error "+this.status+" "+this.statusText);
  }
}
a.send();

回答by user1881928

I prefer to use ajax jquery. Jquery makes live a lot easier.

我更喜欢使用ajax jquery。Jquery 让生活变得更轻松。

What you for example can do on the server side is, i assume you're using php:

例如,您可以在服务器端做的是,我假设您正在使用 php:

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){
    // if it's an ajax request

    $json['success'] = 1;
    $json['html'] = '<div id="test">..[more html code here].. </div>';
    echo json_encode($json);
}else{
    // if it's an non ajax request


}

At the client side you can do the following using jquery ajax:

在客户端,您可以使用 jquery ajax 执行以下操作:

    $.ajax({
          type: "POST",
          url: "[your request url here]",
          data: { name: "JOKOOOOW OOWNOOO" },
          complete: function(e, xhr, settings){
              switch(e.status){
                  case 500:
                     alert('500 internal server error!');
                     break;
                  case 404:
                      alert('404 Page not found!');
                     break;
                  case 401:
                      alert('401 unauthorized access');     
                     break;       
              }
          }           
        }).done(function( data ) {
            var obj = jQuery.parseJSON(data)

            if (obj.success == 1){

                  $('div#insert_html_div').html(obj.html);

            }else if (obj.error == 1){


                            }


            // etc

        });

回答by Brett Zamir

In the past, Ajax was different in different browsers (and still is if you need to support older browsers which a good number of users are unfortunately still using). For older browsers, you would need a library like JQuery (or your own equivalent code) to handle the browser differences. In any case, for a beginner, I might recommend jQuery for good docs, a simple API, and getting started quickly, though MDNis helpful for JavaScript itself too (and you really should increasingly get to understand JavaScript/DOM APIs even if you primarily rely on jQuery).

过去,Ajax 在不同的浏览器中是不同的(如果您需要支持旧的浏览器,但不幸的是,许多用户仍在使用旧浏览器,则仍然如此)。对于较旧的浏览器,您需要像 JQuery(或您自己的等效代码)这样​​的库来处理浏览器差异。在任何情况下,对于初学者,我可能会推荐 jQuery 以获得好的文档、简单的 API 和快速入门,尽管MDN对 JavaScript 本身也有帮助(并且您确实应该越来越多地了解 JavaScript/DOM API,即使您主要是依靠jQuery)。