通过JavaScript的数组的CherryPy与AJAX [英] Pass JavaScript array to cherrypy with AJAX

查看:156
本文介绍了通过JavaScript的数组的CherryPy与AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图发送一个数组的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的部分(我用这个<一href="http://stackoverflow.com/questions/8065913/how-to-send-a-javascript-array-to-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.

这篇关于通过JavaScript的数组的CherryPy与AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆