首页 > 解决方案 > 将ajax数据发布到python函数时遇到问题

问题描述

我有一个 Chrome 扩展,其背景页面包含变量url。我正在尝试将url发送到我的 python 代码,但我在后台日志中得到“400 (BAD REQUEST)”,并且在我的 python 日志中没有错误。

背景.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log("receiving URL");
    console.log(request);
    var articleUrl = request;
    console.log(articleUrl)
    // sending URL to python
    $.ajax({
        type: 'POST',
        url: `${url}/buttoncolor`,
        data: articleUrl,
        success: function myFunction(data) {
        console.log("just sent the url to buttoncolor")
        }
    })

});

应用程序.py:

@application.route('/buttoncolor', methods=['GET', 'POST'])
def buttoncolor():
    print ("buttoncolor")
    if request.method == 'POST':
        if not request.form['articleUrl']:
            flash('Please enter the url field', 'error')
        else:
            rurl = request.form['articleUrl']
            print("here comes rurl")
            print(rurl)

print ("buttoncolor") 工作正常,但 print("here come rurl") 没有出现。我在 background.js 中有另一个带有 $.ajax 的 chrome.runtime.onMessage.addListener,它可以发布并很好地应用于 application.py 中的另一个函数。

标签: javascriptpythonjquerygoogle-chrome-extension

解决方案


修改你的ajax数据

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log("receiving URL");
    console.log(request);
    var articleUrl = request;
    console.log(articleUrl)
    // sending URL to python
    $.ajax({
        type: 'POST',
        url: `${url}/buttoncolor`,
        data:{articleUrl: articleUrl},
        success: function myFunction(data) {
        console.log("just sent the url to buttoncolor")
        }
    })

});

推荐阅读