开发者

passing a javascript array to a django view

I'm using django and have a page of search results that I want to be able to filter by category with ajax (jquery) requests. There's a filter bar on the side of the page and wh开发者_开发百科en someone selects certain categories and clicks submit, those corresponding results should show up on the page. My code looks something like this:

<input type="checkbox" name="category1" value="1" />
<input type="checkbox" name="category2" value="2" />
<input type="button" name="submit" onclick="{
    var cats = new Array();
    $(input[type=checkbox]:checked).each(function() {
        cats.push($(this).val());
    });
    $.getJSON('page.html', {'cats':cats}, function(data) {...});
}" />

But in the django view when I try to read the cats array it returns a 500 error. I can, however, pass scalars and strings to the django view with no problem.

Any thoughts? Is there a more elegant jQuery way to do this without using a javascript array?


Rather than getting the field values manually, you can use jQuery's serializeArray() method, which turns a set of fields into an array which can be sent as JSON. Note that you'll probably want both checkboxes to have the same name, so that when it's serialised it becomes something that Django will interpret as a list.

As Steve says, to help further we'll need to know what the view is doing and what the error is.


Got it working - I downloaded the jquery-json plugin, encoded my array as a json obect to send to django, and then used simplesjon.loads() in the django view to convert that json object to a python list. However, the fact that it took so many steps and jQuery on its own doesn't even come with json encode functionality still makes me think there must be a more elegant way - if anyone has any insight, I'd love to hear it.

Thanks Daniel for pointing me in the right direction.


I guess that a workaround would be transforming your array into a string, eg in javascript:

a = new Array(0,1,2,3,4);
[0, 1, 2, 3, 4]
a.join(" ")
"0 1 2 3 4"

Then you can pass this to the python back end, split it and reconstruct the data structure you need.....

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜