如何将JavaScript数组发送给cherrypy

如何将JavaScript数组发送给cherrypy

本文介绍了如何将JavaScript数组发送给cherrypy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似jQuery的帖子

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

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

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

如何将数组发送给cherrypy?

How can I send an array to cherrypy?

推荐答案

问题是,较新的jQuery版本将花括号作为CherryPy不喜欢的名称的一部分发送.一种解决方案是在CherryPy方面捕获该问题:

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

另一种解决方案是让jQuery使用传统的发送参数方法,通过将传统标志设置为true来序列化参数.下列代码可直接使用CherryPy代码:

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');

这篇关于如何将JavaScript数组发送给cherrypy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 04:11