Advertisement
simbha

gae python ajax post

Oct 9th, 2013
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. # MAIN.PY
  2. # THIS IS THE FUNCTION URL FROM WHERE THE AJAX POST IS DONE:
  3.  
  4. template_dir = os.path.join(os.path.dirname(__file__), 'inc/html/')
  5. jinja = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(template_dir))
  6.  
  7. SETTINGS_PATH = os.path.normpath(os.path.dirname(__file__))
  8. img_dir = os.path.join(SETTINGS_PATH, "inc/req")
  9.  
  10.  
  11. class Test(webapp2.RequestHandler):
  12.     def get(self):
  13.         for file in os.listdir(img_dir):
  14.             h = []
  15.             h.append(file)
  16.             for l in h:
  17.                 r = l.endswith('.jpg') or l.endswith('.png') or l.endswith('.gif')
  18.                 if r == True:
  19.                     dd.append(l)
  20.                     dd.sort()
  21.         template_values = {'images': dd}
  22.         template = jinja.get_template('img.html')               # The HTML file with AJAX.JS file
  23.         self.response.write(template.render(template_values))
  24.  
  25. # THIS CLASS RECEIVES THE AJAX POST
  26. class DoubleNumbers(webapp2.RequestHandler):
  27.     def get(self):
  28.         pass
  29.  
  30.     def post(self):
  31.         self.response.headers['Content-Type'] = 'application/json'
  32.         data = json.loads(self.request.body)
  33.         z = data['imageSrc']
  34.         logging.info(z)
  35.     self.response.write(z)
  36.  
  37. app = webapp2.WSGIApplication([
  38.         ('/tst', Test),             # AJAX POST from URL /tst to URL /i
  39.     ('/i', DoubleNumbers),
  40. ], debug=True)
  41.  
  42. # THE JS FILE
  43.  
  44. $(document).ready(function() {
  45.     $("button").click(function(){
  46.         var data = {'imageSrc' : $(this).parent().find('img').attr('src')};
  47.        
  48.         var request = $.ajax({
  49.             cache: false,
  50.             url: "/i",
  51.             type: "POST",
  52.             data: JSON.stringify(data),
  53.             dataType: "json",
  54.         }).done(function(data){
  55.         var txt = "<!DOCTYPE html><html><body><img src='"+data+"'></body></html>";
  56.         document.open("text/html");
  57.         document.write( txt );
  58.         document.close();
  59.         console.log(data);
  60.         console.log(txt);
  61.         });
  62.     });
  63. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement