Как хранить данные из ajax с помощью webapp2 (python) - PullRequest
0 голосов
/ 19 октября 2019

Я хочу получать данные из ajax, но я получил "None" в качестве моей переменной

class update(webapp2.RequestHandler):
    def post(self):
        print("data",self.request.POST.get('data'))

app = webapp2.WSGIApplication([
 ('/update', update)
], debug=True)
   data= 3;
$.ajax({
    url: "/update",
    data: data, //data=3
    type: "POST",
    success: function( xml ) {
        alert( "It worked!" );
        },
});

Я получил: ('data', '') как результат, когда я ожидал: "data '3' "

Edit: если возможно, оставьте ответ только в одной строке: например: print (" data ", self.request.POST.get ('data'))

1 Ответ

2 голосов
/ 19 октября 2019

Благодаря Beniamin H решение простое.

data= {
   'a':3   // I changed data to a dictionary 
           // edit:you don't need quotes for a, so, a:3 works also
} 
$.ajax({
    url: "/update",
    data: data,
    type: "POST",
    success: function( xml ) { //more edit:xml is the data returned 
        alert( "It worked!" );   //from the webbapp you can name it what 
                               //ever you want

//this gets data from the server
     console.log(xml['a']) //prints out 3
        },
});

class update(webapp2.RequestHandler):
    def post(self):
        data=self.request.POST.get('a')
        print("data: "+data)


#edit: to return a data to javascript, make a dictionary like: 
#    data={
#    'a':3
#    'b':5    #you need quotes i think
#    }
   #and then write:
#  self.response.write(data)

Распечатывается: данные: 3

...