从控制台输出Javascript / Python / Jinja2保存变量

时间:2017-12-30 02:42:10

标签: javascript python

我正在使用Trello API创建一张卡片。这工作正常,但脚本运行时,它会将新创建的卡的ID变量打印到控制台。我想把这个变量带回我的python代码。这可能吗?我使用Jinja2将变量从Python传递给HTML,我可以在这里使用它吗?

这是Chrome中控制台的输出,我想获取第一个ID变量,以便我可以在我的Python代码中使用它。

{
  "id": "5a46fa28620367df83fe08f7",
  "badges": {
    "votes": 0,
    "attachmentsByType": {
      "trello": {
        "board": 0,
        "card": 0
      }
    },
    "viewingMemberVoted": false,
    "subscribed": false,
    "fogbugz": "",
    "checkItems": 0,
    "checkItemsChecked": 0,

这是我的Javascript:

var authenticationSuccess = function() {
  console.log('Successful authentication');
};

var authenticationFailure = function() {
  console.log('Failed authentication');
};

window.Trello.authorize({
  type: 'popup',
  name: 'Work Requests App',
  scope: {
    read: 'true',
    write: 'true' },
  expiration: 'never',
  success: authenticationSuccess,
  error: authenticationFailure
});

//console.log(trelloTitle);
//console.log(trelloContent);

var myList = '5a3ec86f7920a6e66b28e4bc';

var creationSuccess = function (data) {
  console.log('Card created successfully.');
  console.log(JSON.stringify(data, null, 2));

};

//var data = $('#resultsdata').data();
//console.log(trelloId);



var newCard = {
  name: trelloTitle,
  desc: trelloContent,
  // Place this card at the top of our list
  idList: myList,
  idMembers: trelloId,
  pos: 'top'
};


window.Trello.post('/cards/', newCard, creationSuccess);
编辑:我现在正在使用这种AJAX方法:

var creationSuccess = function (data) {
    console.log('Card created successfully.');
    console.log(JSON.stringify(data, null, 2));
    var url = "/ajaxtest";
    $.post(url, {card_id: data.id});
};

我很难将card_id传递给我的python方法:

class AjaxTest(webapp2.RequestHandler):
    def post(self):
        data = card_id

我知道这是错的,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

以下是完整的答案:

var creationSuccess = function (data) {
  console.log('Card created successfully.');

  var http = new XMLHttpRequest();
  var url = "URL to your server (where you want to send the data)";

  http.open("POST", url, true);

  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  http.send("card_id=" + data.id);
};

这会通过AJAX调用将卡ID作为card_id发送到您的服务器(到您指定的URL)。

这假设您只使用纯Javascript。如果您正在使用jQuery,那么进行AJAX调用会更容易。像:

var creationSuccess = function (data) {
  console.log('Card created successfully.');
  var url = "URL to your server";
  $.post(url, {card_id: data.id});
};

编辑:至于服务器代码,您现在可以收到card_id,如下所示:

class AjaxTest(webapp2.RequestHandler):
    def post(self):
        data = self.request.get('card_id')

希望有所帮助。