Getting json file using jQuery without web server

I had a survey for coding interviews for interfaces that work with JSON and something else. I sent my file, but I just wanted to know what was missing.

And one of the questions was Should not require a web server, and should be able to run offline. .

I used jQuery and used $.getJSON() to get data from a .JSON file. I threw it on a local WAMP server and it worked flawlessly in all three main browsers (IE, Firefox, Chrome). Then I moved this project to Desktop , so essentially without LOCALSERVER.

In Firefox 30.0, it worked great. No problems.

Oon Google Chrome, I know that you cannot access local files without a web server ...

In Internet Explorer 11, however ... this did not work. Why?

Here is what I use. It's not hard.

 function loadTasks() { console.log("Loading tasks..."); $.getJSON("data.json", function(result) { $.each(result, function(i, task) { $("#load_tasks").append( "<div class='row'><span class='data-task'>" + task.name + "</span> <span class='data-date'>" + task.date + "</span> <span class='data-name'>" + task.assigned + "</span> </div>"); }); }); } 

and here data.json

+7
json javascript jquery internet-explorer jquery-data
source share
10 answers

This seems like a bug in jQuery. This error is reported in jQuery. Error status is fixed. But it seems that the error is still at large.

Explanation

Typically, in IE, ajax is implemented through ActiveXObjects . But in IE11, they made some changes to the ActiveXObject implementation if we try to do the following:

 typeof(window.ActiveXObject) 

instead of returning 'function', as said in IE docs , it returns undefined . jQuery is used to switch between xhr in regular browsers and between IE in IE. Since the check is evaluated as undefined, the code used to create the xhr object is executed in regular browsers (which, of course, is an error, since it works fine for non-local files).

In the bug registered at bugs.jquery.com , the error reporter asks:

To fix the problem, just change it: use "window.ActiveXObject! == undefined?" instead of "window.ActiveXObject?"

JQuery developers are trying to fix this with this commit , but the comment in the commit says it is still not fixed, and also offers a possible way to approach this issue.

 var activex; // save activex somewhere so that it only need to check once if ( activex === undefined ) try { new ActiveXObject("MSXML2.XMLHTTP.3.0"); activex = true; } catch (e) { activex = false } xhr = activex ? createActiveXHR() : createStandardXHR(); 
+5
source share

I tried running my code on my machine and it works fine in IE. However, if this does not work on your computer, there should be a problem with the IE settings. Other than that, if you want to read the local file, you can try the code below to solve this problem for IE

 function showData(){ function getLocalPath(fileName/*file name assuming in same directory*/){ // Remove any location or query part of the URL var directoryPath = window.location.href.split("#")[0].split("?")[0]; var localPath; if (directoryPath.charAt(9) == ":") { localPath = unescape(directoryPath.substr(8)).replace(new RegExp("/","g"),"\\"); } localPath = localPath.substring(0, localPath.lastIndexOf("\\")+1)+fileName; console.log(localPath); return localPath; } var content = null; try { var fileSystemObj = new ActiveXObject("Scripting.FileSystemObject"); var file = fileSystemObj.OpenTextFile(getLocalPath("data.json"),1); content = file.ReadAll(); file.Close(); } catch(ex) { console.log(ex); } console.log(content); } showData(); 

Run the html file in the browser from the file path and try to run the above function in the console. It will display the contents of the json file in the console.

You can create a wrapper for the above code for use in an XHR request. Let me know if you need help integrating this with jQuery AJAX request.

+3
source share

What you are missing is the use of appCache,

 <html manifest="example.appcache"> 

in your HTACCESS add

 AddType text/cache-manifest .appcache 

inside example.appcache

 CACHE MANIFEST data.json index.php someimage.png # continue for all the file needed for the web site to work 

This means that after you have connected and downloaded the content, as soon as it is not needed again. on another note that you should not have access to the URI file:// , although XHR / ajax, since there is no way to send content, if you want to disable it, you could just insert the contents of the json file into your code as a string and just use var jsonStr = '{}'; var jsonObj = JSON.parse(jsonStr); var jsonStr = '{}'; var jsonObj = JSON.parse(jsonStr); where jsonStr is the code. this would mean no connection to the server since there would be no ajax / XHR request

+1
source share

jQuery.getJSON uses ajax. http://api.jquery.com/jquery.getjson/

.ajax uses XMLHttpRequest

Web security chrome and other browsers blocks XMLHttpRequest to local files because it is a security issue.

Through the depth of security: local web pages

http://blog.chromium.org/2008/12/security-in-depth-local-web-pages.html

You receive an email from an attacker containing a web page as the application you are downloading.

You open a local web page in your browser.

The local web page creates an iframe, the source of which is https://mail.google.com/mail/ .

Since you are logged in to Gmail, the frame uploads messages to your inbox.

The local web page reads the contents of the frame using JavaScript to access frames [0] .document.documentElement.innerHTML. (An Internet web page cannot complete this step because it comes from a non-Gmail source; a policy of the same origin will result in a read for failure.)

The local web page puts the contents of your mailbox in and sends the data through the POST form to the attacker's web server. Now the attacker has your mailbox, which can be useful for sending spam or identify theft.

The solution for data that does not need a security policy of the same origin is complemented by json. Since jsonp is not a safe data format. Jsonp does not have policies of the same origin.

 /* secured json */ { "one": "Singular sensation", "two": "Beady little eyes", "three": "Little birds pitch by my doorstep" } /* padded json aka jsonp */ Mycallback ({ "one": "Singular sensation", "two": "Beady little eyes", "three": "Little birds pitch by my doorstep" }); 

Since with jsonp json is wrapped in a valid javascript function, it can be opened just like anyone who adds any javascript to the page.

 var element = document.createElement("script"); element.src = "jsonp.js"; document.body.appendChild(element); 

And your callback processes the data,

 function Mycallback(jsondata) { } 

This is functionally the same as the ajax request, but different because it is a jsonp request, which is actually simpler.

jQuery libs directly support jsonp, and http://api.jquery.com/jquery.getjson/ See an example using the Flickr JSONP API; unless double standards were known, they might not even notice that jsonp was being used.

 (function() { /* jsonp request note callback in url, otherwise same json*/ var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?"; $.getJSON( flickerAPI, { tags: "mount rainier", tagmode: "any", format: "json" }) .done(function( data ) { $.each( data.items, function( i, item ) { $( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" ); if ( i === 3 ) { return false; } }); }); })(); 

Local access to json can be enabled, but it does it differently depending on browswer.

Use --allow-file-access-from-files to include it in chrome. https://code.google.com/p/chromium/issues/detail?id=40787

FYI: they are working on encripted json http://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-08 I am absolutely sure that there will be no method of using this locally. to make it really safe.

+1
source share

Source: stack overflow

Posting a response in case someone else comes across it. In my case, IE was loading a version of jquery that apparently calls "JSON undefined". Here is what I did to solve it:

 <!--[if lt IE 9]> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <![endif]--> <!--[if gte IE 9]><!--> <script src="http://code.jquery.com/jquery-2.0.3.js"></script> <!--<![endif]--> 

Last jquery 2.1.1 : direct link , but that says:

(IE <9 is not supported)

So i think jquery 1.11.1 : direct link

And I found out that you can create ajax and jquery things in Chrome on local files if you use Chrome with this flag: --allow-file-access-from-files (source)

0
source share
 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 

Try adding this meta tag and check IE

0
source share

Here is a working solution. I turned on the steering wheel because it is cleaner.

 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>JSON TEST</title> </head> <body> <div id="load-tasks"> </div> <script src="jquery.min.js"></script> <script src="handlebars.min.js"></script> <script id="tasks-template" type="text/x-handlebars-template"> {{#each .}} <div class="row"> <span class="data-task"> {{this.name}} </span> <span class="data-date"> {{this.date}} </span> <span class="data-name"> {{this.assigned}} </span> </div> {{/each}} </script> <script> $(function () { var loadTasksContainer = $('#load-tasks'), tasksTemplate = Handlebars.compile($('#tasks-template').html()); $.ajax({ type: "GET", url: "data.json", dataType: "json", cache: false, success: function (data) { var html = tasksTemplate(data); loadTasksContainer.append(html); }, error: function (xhr, status, error) { //log error and status } }); }); </script> </body> </html> 
0
source share

Using JSONP, you can do this work for all browsers with or without a web server, or even with a cross-domain.

Example data.jsonp file:

 loadTasks([ {name:"Task 1", date:"Date 1", assigned:"John Doe"}, {name:"Task 2", date:"Date 2", assigned:"Jane Doe"} ]); 

Then on your page just load data.jsonp with the script tag:

 <script> function loadTasks(tasks) { $.each(tasks, function (i, task) { $("#load_tasks").append( "<div class='row'><span class='data-task'>" + task.name + "</span> <span class='data-date'>" + task.date + "</span> <span class='data-name'>" + task.assigned + "</span> </div>"); }); } </script> <script src="data.jsonp"></script> 
0
source share

Try turning on the error callback; jqxhr.responseText may contain data.json .

data.json

 {"data":{"abc":[123]}} 

json.html

 <!DOCTYPE html> <html> <head> <script type="text/javascript" src="jquery-1.11.1.min.js"></script> <script type="text/javascript"> $(function() { $.getJSON(document.location.protocol + "data.json") .then(function(data, textStatus, jqxhr) { var response = JSON.parse(data); console.log(textStatus, response); } // `error` callback , function(jqxhr, textStatus, errorThrown) { var response = JSON.parse(jqxhr.responseText); console.log(textStatus, errorThrown, response); $("body").append(response.data.abc); }); }) </script> </head> <body> </body> </html> 
0
source share

Dealing with this problem will take you anywhere. This is a complex task and can be easily solved using any http server.

If your problem is that it is difficult to configure, try the following: https://www.npmjs.org/package/http-server

On your shell, you will go to the directory where your files are located, and then just type

 http-server ./ -p 12345 

where 12345 can be changed by any valid and unused port of your choice.

0
source share

All Articles