Reputation: 4393
I'm using ajax call to load data to my application. its working fine for paths like this
../../DataSource/newJson.json
but it doesn't work for the path like this.
C:\Users\acer\Desktop\NewJson.json
I have searched a lot but i didn't find any proper solutions to my question. I'm using the following code to load the file from the local directory.
<button id="loadData">update new Json</button>
<input type="file" id="newJson" value="file" />
Here is my ajax call:
$("#loadData")[0].onclick= function (e){
$.holdReady(true);
var request = $.ajax({
type: "GET",
dataType: 'json',
url: $("#newJson").val(),
success: function (data) {
alert('success')
},
error: function (data, dat1, error) {
alert(error)
}
});
};
Any suggestions should be appreciated.
Upvotes: 1
Views: 2388
Reputation: 36995
What browsers do you need to support? For modern browsers you can use HTML5 File API. For browsers that don't support it one option is a round-trip to a server (upload the file and return its contents), or a polyfill like https://github.com/Jahdrien/FileReader
An example using File API: (fiddle)
// check for support
if (window.File && window.FileReader && window.FileList && window.Blob) {
// event handler to fire when file input changes
function handleFileSelect(evt) {
var file = evt.target.files[0],
reader = new FileReader(),
contents;
if( file ){
reader.onload = function(f){
contents = f.target.result;
console.log( contents ); // here you'd use JSON.parse on the contents
};
reader.readAsText(file);
}
}
// attach the event listener. It'll fire immediately, without clicking on the other button.
document.getElementById('newJson').addEventListener('change', handleFileSelect, false);
} else {
console.log( 'File API not supported, sorry' )
}
Learn more: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Upvotes: 0
Reputation: 944320
There are several reasons that this won't work:
file://
URIs do not use exactly the same syntax as local directory pathsIf you want to access files selected by the user using a file input, then use the Files API (but note limited browser support).
Upvotes: 1