2011-11-09 67 views
1

我有一個jQuery後像如何發送一個javascript數組CherryPy的

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

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

而且它進入一個cheerypy功能:

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

但是運行的JavaScript回報400 Bad Request因爲Unexpected body parameters: values[]

如何將數組發送給cherrypy?

回答

7

問題是,較新的jQuery版本發送大括號作爲CherryPy不喜歡的名稱的一部分。一個解決方案是趕上這在CherryPy的一面:

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

另一種解決方案是讓jQuery的使用與傳統的標誌設置爲true序列化PARAMS發送則params的傳統方法。以下工作與CherryPy代碼不變:

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

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

我有一個相關的問題。你的回答幫助了我,但我仍然需要幫助。你願意看看我的問題嗎? [鏈接](http://stackoverflow.com/questions/23463617/pass-javascript-array-to-cherrypy-with-ajax) –

相關問題