通过JavaScript的数组的CherryPy与AJAX数组、JavaScript、AJAX、CherryPy

由网友(↗缘份)分享简介:我试图发送一个数组的CherryPy,但事实证明是空的。I'm trying to send an array to cherrypy but it turns out empty.这是我的js文件。我检查和数组被填充,因为它应该。This is my js file. I've checked and the...

我试图发送一个数组的CherryPy,但事实证明是空的。

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

这是我的js文件。我检查和数组被填充,因为它应该。

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

});

这是CherryPy的部分(我用这个answer作为一个准则)

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)

这是从Python code被称为上面

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)    

在这里我的目标是将数据保存到一个XML文件中。我已经成功地保存到具有类似code中的XML文件。现在的问题是,在for循环提醒是空的,这意味着数组没有通过使用Ajax调用(至少这是我的猜测)。

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).

有什么想法?

推荐答案

您应该叫 $ AJAX 简单地数据:{警报:alert_ids JSON.stringify:} 数据,而不是。({警报:alert_ids})

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

此外,删除的contentType:应用/ JSON,行。 CherryPy的曝光方法需要的形式,urlen codeD格式,而不是JSON。

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

如果您设置传统:真正的,你不能在警报参数的CherryPy后加括号,否则你必须添加它们。

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

阅读全文

相关推荐

最新文章