我正在使用JSON传输数据。
我的HTML页面中需要什么才能读取一个只包含一个JSON对象的Ajax文件到我的脚本中?
我是否也需要jQuery,或者是否可以使用Ajax加载该JSON文件?
在不同的浏览器上有所不同吗?
答案 0 :(得分:53)
您不需要任何库,所有内容都可以在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);
});
答案 1 :(得分:3)
最有效的方法是使用纯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();
答案 2 :(得分:1)
过去,Ajax在不同的浏览器中有所不同(如果您需要支持旧版浏览器仍然存在,很多用户仍然使用这些浏览器)。对于旧版浏览器,您需要一个像JQuery(或您自己的等效代码)这样的库来处理浏览器差异。在任何情况下,对于初学者,我可能会推荐jQuery用于优秀的文档,一个简单的API,并快速入门,尽管MDN对JavaScript本身也有帮助(你真的应该越来越多地理解JavaScript / DOM API即使你主要依赖jQuery)。
答案 3 :(得分: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
});