20

我正在使用 JSON 传输数据。

我需要在我的 HTML 页面中使用 Ajax 读取在我的脚本中只包含一个 JSON 对象的文件吗?

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

不同浏览器有区别吗?

4

4 回答 4

60

您不需要任何库,所有东西都可以在 vanilla javascript 中获取并解析它:

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);
});
于 2013-01-17T21:32:44.560 回答
4

最有效的方法是使用纯 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();
于 2013-01-17T21:33:01.240 回答
1

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

于 2013-01-17T21:32:37.620 回答
1

我更喜欢使用 ajax jquery。Jquery 让生活变得更容易。

例如,您可以在服务器端执行的操作是,我假设您使用的是 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


}

在客户端,您可以使用 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

        });
于 2013-01-17T22:51:20.363 回答