Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top