我正在通过Django开发一个Web应用程序,我想从我的JavaScript到Django视图中获取信息,以便访问数据库。

我正在将ajax调用用作this post shows
我通过onclick事件在html中调用js:

sortedTracks.html

     ...
    <form action="{% url 'modelReco:sortVideo' video.id %}">
        <input type="submit" value="Validate" onclick="ajaxPost()" />
    </form>
    ...


clickDetection.js

//defined here
var tracksSelected = [];

//function that fill tracksSelected
function tagTrack(track_num){
  if(tracksSelected.includes(track_num)){
    var index = tracksSelected.indexOf(track_num);
    tracksSelected.splice(index, 1);
  }else{
      tracksSelected.push(track_num);
  }};

//ajax function
function ajaxPost(){
$.ajax({
    method: 'POST',
    url: '/modelReco/sortedTracks',
    data: {'tracksSelected': tracksSelected},
    success: function (data) {
         //this gets called when server returns an OK response
         alert("it worked! ");
    },
    error: function (data) {
         alert("it didnt work");
    }
});
};


所以我要传输的信息是tracksSelected,并且是一个像[21,150,80]这样的int数组

views.py

def sortedTracks(request):
if request.is_ajax():
    #do something
    print(request)
    request_data = request.POST
    print(request_data)

    return HttpResponse("OK")


Ajax发布工作良好,但我得到的答案只是一个空的查询字典,像这样:
<QueryDict: {}>
如果我打印请求,我得到:

<WSGIRequest: GET '/modelReco/sortedTracks/?tracksSelected%5B%5D=25&tracksSelected%5B%5D=27&tracksSelected%5B%5D=29'>

我也尝试过更改为request_data=request.GET,但结果却很奇怪,其中数据现在位于tracksSelected[]

最佳答案

我试图知道为什么我要执行request_data=request.GET时,会得到像这样的数据tracksSelected[],而只得到它的最后一个元素。

而且我找到了一种避免在数据中包含数组的方法(tracksSelected)on this link
这使我拥有:

在views.py中

def sortedTracks(request):
if request.is_ajax():
    #do something
    print(request)
    request_data = request.GET.getlist("tracksSelected")[0].split(",")
    print(request_data)


在clickDetection.js中

function ajaxPost(){
tracksSelected = tracksSelected.join();
$.ajax({
    method: 'POST',
    url: '/modelReco/sortedTracks',
    data: {'tracksSelected': tracksSelected},
    success: function (data) {
         //this gets called when server returns an OK response
         alert("it worked! ");
    },
    error: function (data) {
         alert("it didnt work");
    }
});
};


这个小技巧有效,我能够获得像这样的数组数据,
print(request_data)返回我的数组,例如[21,25,27]

感谢你们对我的帮助 !

09-06 08:30