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

时间:2022-10-12 18:13:57

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页面中,我需要什么来读取一个只有一个JSON对象的Ajax文件呢?

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?

不同的浏览器有什么不同吗?

4 个解决方案

#1


48  

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

您不需要任何库,所有可用的都可以在普通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);
});

#2


3  

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();

#3


1  

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 MDN is 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本身也有帮助(即使您主要依赖jQuery,您也应该逐渐了解JavaScript/DOM API)。

#4


1  

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

        });

#1


48  

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

您不需要任何库,所有可用的都可以在普通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);
});

#2


3  

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();

#3


1  

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 MDN is 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本身也有帮助(即使您主要依赖jQuery,您也应该逐渐了解JavaScript/DOM API)。

#4


1  

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

        });