【问题标题】:How to store data from ajax with webapp2(python)如何使用 webapp2(python) 存储来自 ajax 的数据
【发布时间】:2023-03-11 09:25:02
【问题描述】:

我想从 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'”

编辑:如果可能,请将答案保留在一行中:例如: print("data",self.request.POST.get('data'))

【问题讨论】:

  • 你尝试.getall而不是.get self.request.POST 吗?
  • 如果您的数据实际上是数字 3,也可能会出现问题。根据 jQuery 文档,数据应该是对象、字符串或数组,例如:{'a': 3}
  • 成功了!但是我如何传递一个数组?也没有返回的 Cus
  • 如果你传递一个数组,你就不能像字典一样访问它。我想self.request.POST 将是一个列表。
  • 那是正确的,然后我尝试循环遍历数组并逐个发送每个元素,但这弄乱了顺序

标签: javascript python jquery ajax webapp2


【解决方案1】:

感谢 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

【讨论】:

    猜你喜欢
    • 2018-12-04
    • 2019-08-31
    • 2022-01-02
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2021-09-29
    • 1970-01-01
    相关资源
    最近更新 更多