I trying to send un object from a view to controller (Web2py) in the same 
way that:

http://stackoverflow.com/questions/1719244/how-to-pass-a-json-object-to-web2py-using-jquery-ajax
In the ajax part I get the string: 

    {
       "testObject":{
          "value1":"value1value!",
          "value2":"value2value!"
       }
    }

using the json.js from 
https://sites.google.com/site/jollytoad/json.js?attredirects=0

Then I have this code:
                           

     $.ajax({
          type: 'POST',
          url: '{{=URL('default', 'jsontest.json')}}',
          contentType: "application/json; charset=utf-8",    
          data: data,
          dataType: 'json',
          success:  function(data){  alert('yay'); }
                                });
On the other hand my jsontest function has this def in the default.py:

    def jsontest():
       
       import gluon.contrib.simplejson
       data = gluon.contrib.simplejson.loads(request.body.read())
       
       import os
       myfile = os.path.join(request.folder, 'static', 'file1.txt')
       f = open(myfile, "w")       
       f.write(data)
       f.close()
       return dict()


I think the part of $ajax... is correct because sometimes I get the alert 
of yay and also when it works the file1.txt is created. The problem is: I 
don't know how to read the objet sent to the controller. I don't know whats 
is request.body.read, what is data in jsontest? I put data in f.write but 
the content of the file1.txt is empty. Is it necessary to import other 
thing  beside import gluon.contrib.simplejson?
any sugestions? thanks

TEST: I have tested in jsontest :
  

    import gluon.contrib.simplejson
      data = gluon.contrib.simplejson.loads(request.body.read())
    
     import json
       ss=json.dumps('[{"foo": "bar"}, {"fubar": "snafu"}]')
       dd=json.loads(ss)
     import os
       myfile = os.path.join(request.folder, 'static', 'file1.txt')
       f = open(myfile, "w")       
       f.write(dd)
       f.close()

and now the file1 is not empty: I have [{"foo": "bar"}, {"fubar": "snafu"}]
I am getting also the alert yay

 Anybody has a sugestion why data is empty?

-- 



Reply via email to