如何将javascript数组发送到cherrypy

Mat*_*len 1 python jquery cherrypy

我有一个类似的jQuery帖子

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

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

它涉及一个cheerypy功能:

@cherrypy.expose
def saveTheValues(self, values=None):
    #code to save the values
Run Code Online (Sandbox Code Playgroud)

但运行javascript返回400 Bad Request是因为Unexpected body parameters: values[].

如何将数组发送到cherrypy?

Cit*_*ito 7

问题是较新的jQuery版本将大括号作为CherryPy不喜欢的名称的一部分发送.一个解决方案是在CherryPy端抓住这个:

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

另一种解决方案是让jQuery使用传统方法发送参数,方法是将传统标志设置为true来序列化params.以下适用于CherryPy代码:

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

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