首页 > 解决方案 > POST jQuery 方法工作但不返回 JSON 响应

问题描述

我正在尝试将 JSON 响应保存为我的 POST 请求中的变量。前端脚本将 POST 发送到 API,然后将其传递给 Trello 以创建新板。该板已成功创建,并且我从 Trello 到 API 获得了 JSON 响应。当我尝试将相同的响应传递给前端时,它似乎不起作用。我一般不太了解 javascript 和前端,所以我认为我在这里的 jQuery 做错了,但我不确定。

这是 jQuery 请求:

function submit(boardname){
  $.ajax({
    type: 'POST',
    url: `/trello/${boardname}`,
    dataType: "json",
    success: function(data){
      console.log('Success', data)
      $('#response').html(data)
  }
});
}

$("#submit").click(function(){
  let name = document.getElementById("board-name-input").value
  submit(name)
});

这是我对 trello 的 API 发布函数(使用 Flask-restful):

class TrelloBoard(Resource):
    @check_token
    # create public board with default list
    def post(self, name):
        try:
            url = f'https://api.trello.com/1/boards/'
            query = {
                'key':'mykey',
                'token':'mytoken',
                'name':f'{name}',
                'defaultLists':'true',
                'prefs_permissionLevel':'public'
            }
            response = requests.post(url, params=query)
            print(f'Response: {response.json()}')
            return response.json() 
        except:
            return {"message": "Unexpected error ocurred."}, 500

编辑,这是服务器上的响应:

127.0.0.1 - - [10/Dec/2020 00:02:10] "GET /trello HTTP/1.1" 200 -
Response: {'id': '5fd1658238fc9278a577c913', 'name': 'test', 'desc': '', 'descData': None, 'closed': False, 'idOrganization': '5fcbfac3eb5f7a81b67c3570', 'idEnterprise': None, 'pinned': False, 'url': 'https://trello.com/b/bPvx3oGp/test', 'shortUrl': 
'https://trello.com/b/bPvx3oGp', 'prefs': {'permissionLevel': 'public', 'hideVotes': False, 'voting': 'disabled', 'comments': 'members', 'invitations': 'members', 'selfJoin': True, 'cardCovers': True, 'isTemplate': False, 'cardAging': 'regular', 'calendarFeedEnabled': False, 'background': 'blue', 'backgroundImage': None, 'backgroundImageScaled': None, 'backgroundTile': False, 'backgroundBrightness': 'dark', 'backgroundColor': '#0079BF', 'backgroundBottomColor': '#0079BF', 'backgroundTopColor': '#0079BF', 'canBePublic': True, 'canBeEnterprise': True, 'canBeOrg': True, 'canBePrivate': True, 'canInvite': True}, 'labelNames': {'green': '', 'yellow': '', 'orange': '', 'red': '', 'purple': '', 'blue': '', 'sky': '', 'lime': '', 'pink': '', 'black': ''}, 'limits': {}}

我想将此数据保存在一个变量中,以便在创建板时显示指向板的链接

标签: jqueryhttp-postflask-restful

解决方案


推荐阅读