reading input file from server and displaying output on client side
I have to read a file from server side . Obtained its contents stored it in a list and sent it to template Now, My question is how to access this list so as to display the contents of files line by line . I am using ajax and jquery to obtain the data on client side
def sh开发者_如何学Cowfiledata(request):
f = open("/home/tazim/webexample/test.txt")
list = f.readlines()
return_dict = {'list':list}
json = simplejson.dumps(list)
return HttpResponse(json,mimetype="application/json")
I would do it like this:
var target = $('p.target');
$.getJSON("filedata.json", function(json){
$.each(json.list, function (i, line) {
$('<span></span>')
.html(line)
.appendTo(target);
});
Provided your "file on the server" is HTML (say NEWS.html) and you want to use jQuery ...
make a
<div id="NailMeHere"><!-- filled by Ajax call --></div>
in your doc and execute following code on page load
$(document).ready(function(){
$('#NailMeHere').load("NEWS.html");
});
your NEWS.html may contain your site's CSS, links, everything ....
Based on the HTTP method you can use the jQuery.ajax() function.
I'm not sure how that list
data is formatted, a simple way would be to log the json object with JavaScript itself once it's returned by the ajax call.
There's many ways of displaying JSON objects structure, the easiest would be to use a tool such as FireBug, and use the appropriate console.log();
function.
Otherwise you can simply loop the object, to whichever level you're interested in.
Also many browsers support ({some:'obj'}).toSource();
class FileByLine(object):
def __init__(self, file_object):
self.f = file_object
def next(self):
# do some line format like <li>line</li>
data = self.f.readline()
if data:
return data
else:
raise StopIteration
def __iter__(self):
return self
In action:
return HttpResponse(FileByLine(open('/path/file')))
In JS:
$('#lines_from_file').load("<action url>")
Also you may try http streaming methods http://ajaxpatterns.org/HTTP_Streaming
精彩评论