I am trying to send a object with an array inside of it via an AJAX POST in Django when the user clicks a button. I am following the instructions on the Django docs have hit a snag. I am attempting to see a specific indice in the array using logger.debug()
in the view and am not able to access the contents. How do I access that specific element in the array?
我试图在用户点击按钮时通过Django中的AJAX POST发送一个带有数组的对象。我按照关于Django文档的说明进行了尝试。我试图在视图中使用logger.debug()查看数组中的特定indice并且无法访问内容。如何访问数组中的特定元素?
My AJAX...
我的AJAX ......
var tags_selected = [1,2,3,4]
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$("#filter").click(function(){
$.ajax({
type: 'POST',
url: "/pensieve/filtertags",
data: {'tags': tags_selected},
success: function(res){
console.log(res)
},
dataType: "json"
});
})
My View...
我的看法...
def filter_tags(request):
logger.debug(request.POST)
return HttpResponse(json.dumps({'response': 111}), content_type="application/json")
My DEBUG log in my terminal...
我的DEBUG登录我的终端...
DEBUG - 2016-05-06:17:15:50 - <QueryDict: {u'tags[]': [u'142', u'122', u'138']}>
1 个解决方案
#1
2
You can get values of the tags[]
Array with getlist()
method.
您可以使用getlist()方法获取tags [] Array的值。
Example :
示例:
request.POST.getlist('tags[]')
# outputs : ['1', '2', '3']
request.POST.getlist('tags[]')[1]
# outputs : '2'
#1
2
You can get values of the tags[]
Array with getlist()
method.
您可以使用getlist()方法获取tags [] Array的值。
Example :
示例:
request.POST.getlist('tags[]')
# outputs : ['1', '2', '3']
request.POST.getlist('tags[]')[1]
# outputs : '2'