How to send a javascript array to cherrypy

爱⌒轻易说出口 提交于 2019-12-11 12:48:23

问题


I have a jQuery post something like

var arr = ['some', 'string', 'array'];

jQuery.post('saveTheValues', { 'values': arr },
            function(data)
            {
                //do stuff with the returned data
            }, 'json'
           );

And it goes to a cheerypy function:

@cherrypy.expose
def saveTheValues(self, values=None):
    #code to save the values

But running the javascript returns 400 Bad Request because Unexpected body parameters: values[].

How can I send an array to cherrypy?


回答1:


The problem is that newer jQuery versions send the braces as part of the name which CherryPy doesn't like. One solution is to catch this on the CherryPy side:

@cherrypy.expose
def saveTheValues(self, **kw):
    values = kw.pop('values[]', [])
    #code to save the values

Another solution is to let jQuery use the traditional method of sending params by serializing the params with the traditional flag set to true. The following works with the CherryPy code unaltered:

var arr = ['some', 'string', 'array'];

jQuery.post('saveTheValues', $.param({'values': arr}, true),
    function(data)
    {
        //do stuff with the returned data
    }, 'json');


来源:https://stackoverflow.com/questions/8065913/how-to-send-a-javascript-array-to-cherrypy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!