Pass JavaScript array to cherrypy with AJAX

三世轮回 提交于 2019-12-11 10:57:22

问题


I'm trying to send an array to cherrypy but it turns out empty.

This is my js file. I've checked and the array gets filled as it should.

$(function () {
$('#mark-read').on('click', function (e) {

    alert_ids = [];
    $("input:checkbox[name=alert-cb]:checked").each(function() {
        alert_ids.push($(this).attr('id'));
    });

    $.ajax({
      type: 'POST',
      url: 'markasread',
      data: { alerts: alert_ids },
      traditional: true,
      success: function (data) {
        alert(data);            
      }
    });
});

});

This is the cherrypy part (I used this answer as a guideline)

@cherrypy.expose    
def markasread(self, **alerts_ids):

    """ Mark alerts as read """

    a_ids = alerts_ids.pop('alerts[]', [])
    alerts.mark_as_read(a_ids)

    return json.dumps(a_ids)

And this is the function being called from the python code above

def mark_as_read(alerts):
  alerts_file = ET.parse(ALERTS_FILE)
  root = alerts_file.getroot()  

  for a_id in alerts:
    alert = root.find("./alert[@id='" + a_id + "']")
    alert.set('status', 'watched')

  alerts_file.write(ALERTS_FILE)    

My goal here is to save data to an xml file. I've managed to save to the xml file with similar code. The problem is that 'alerts' in the for loop is empty, which means that the array didn't pass with the ajax call (at least that's my guess).

Any thoughts?


回答1:


You should call $.ajax simply with data: {alerts: alert_ids} instead of data: JSON.stringify({alerts: alert_ids}).

Also, remove the contentType : "application/json", line. CherryPy exposed methods expect form-urlencoded format, not json.

If you set traditional: true, you must not add the braces after the alerts parameter in CherryPy, otherwise you must add them.



来源:https://stackoverflow.com/questions/23463617/pass-javascript-array-to-cherrypy-with-ajax

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