导读:今天首席CTO笔记来给各位分享关于django前端怎么把对象传到后端的相关内容,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
请问前端利用ajax如何把不同的多个对象传到后台,后台如何接收呢?
前端用数组对象将商品入库相关信息格式存储,然后用ajax传给后台,后台(例php使用json_decode转化为数组,然后循环数组并,用户对应关系可以从session中取出当前登录用户id和名称)处理数据获得用户对应的每条购买记录,并执行入库操作
怎么把前端object对象传递给后台
使用ajax发送json给后台。 $.ajax({ type:'POST', url : xxx.action", data : {"list" : '把list拼成json数据'}, dataType : "json", success : function(data){ //成功处理 }, error : function(){ //错误代码 } });
django 怎么把一个字典传递给后端
这个东西的升级:1、你要对整个后端的代码非常熟悉,用到那些Django特性一清二楚。2、官方有upgradeguide之类的文档,根据所用特性照着改就行了。
Django接受前端数据的几种方法
字符型
字符型的数据相对好获取,前端传递的方法如下:
sendData = { "exporttype": exporttype,
"bugids": bugids,
"test": JSON.stringify({"test": "test"})
};
在Django的后端只要使用exporttype = request.GET.get("exporttype")
就能正常的获取到这个数据了。
注意: 在Python2.7中数据是unicode编码的,如果要使用,有时候需要进行转str
结果示例:
Excle type 'unicode'
数组型
获取数组型的数据如果使用获取字符串的数据的方法,打出的结果是None。我们要使用这个方法:
bugids = request.GET.getlist("bugids[]")
这样获取的数据就是数组类型。
注意: 获取的数组中的元素是unicode编码的,在某些时候使用需要转编码
结果示例:
•传递的url
[14/Jul/2016 11:00:41]"GET /testtools/exportbug/?exporttype=Exclebugids%5B%5D=102bugids%5B%5D=101bugids%5B%5D
•获取的数据
[u'102', u'101', u'100', u'99', u'98', u'97', u'96', u'95', u'94', u'93', u'92', u'91', u'90', u'89', u'88', u'87'
字典型
字典型数据其实可以当成字符串数据来处理,获取到对应字符串后使用JSON模块做一下格式化就行了。
对于前端来说,传递字典型的数据就是传递JSON数据,所以使用的方法是:
"test": JSON.stringify({"test": "test"})
结果示例:
{"test":"test"} type 'unicode'
相关源码
•Get方法
Get方法是wsgi里面的一个方法。
def GET(self):
# The WSGI spec says 'QUERY_STRING' may be absent.
raw_query_string = get_bytes_from_wsgi(self.environ, 'QUERY_STRING', '')
return http.QueryDict(raw_query_string, encoding=self._encoding)
最终返回的是一个http.QueryDict(raw_query_string, encoding=self._encoding)http的原始数据,而QueryDict继承于MultiValueDict ,所以我们直接看MultiValueDict就好了。
•MultiValueDict
其实源码看起来并不难。
def get(self, key, default=None):
"""
Returns the last data value for the passed key. If key doesn't exist
or value is an empty list, then default is returned.
"""
try:
val = self[key]
except KeyError:
return default
if val == []:
return default
return val
def getlist(self, key, default=None):
"""
Returns the list of values for the passed key. If key doesn't exist,
then a default value is returned.
"""
try:
return super(MultiValueDict, self).__getitem__(key)
except KeyError:
if default is None:
return []
return default
def __getitem__(self, key):
"""
Returns the last data value for this key, or [] if it's an empty list;
raises KeyError if not found.
"""
try:
list_ = super(MultiValueDict, self).__getitem__(key)
except KeyError:
raise MultiValueDictKeyError(repr(key))
try:
return list_[-1]
except IndexError:
return []
结语:以上就是首席CTO笔记为大家整理的关于django前端怎么把对象传到后端的相关内容解答汇总了,希望对您有所帮助!如果解决了您的问题欢迎分享给更多关注此问题的朋友喔~