将参数从Javascript传递到Python函数

时间:2015-12-03 05:11:58

标签: javascript jquery python ajax flask

我正在尝试从Ajax Call中执行/调用python方法(带有一个参数)。但我无法将参数从Ajax调用传递给Python函数。我正在使用Flask来连接两者。

更新代码: Ajax Call(Javascript):

$.ajax({
    type: 'GET',
    url: "http://127.0.0.1:5000/get_result/" + input.value,
    dataType: "text",
    success: function(response) {
        output.value = response;
        alert(response);
    }
}).done(function(data){
        console.log(data);
});

Python代码:

from flask import Flask
app = Flask(__name__)

@app.route("/get_result/<url>", methods=['GET', 'POST'])
def get_result(url):
    return "Hello World"

if __name__ == "__main__":
    app.run(debug = True)

我有一个在本地运行的后端Python服务器。但我得到这个错误。 (直接从浏览器运行http://127.0.0.1:5000/get_result/google.com会显示正确的结果,如果有帮助的话)。

[预期的最终结果:警告框中包含消息“Hello World”]

错误:

127.0.0.1 - - [03/Dec/2015 13:38:21] "GET /get_result/google.com HTTP/1.1" 200 -
Error on request:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 194, in run_wsgi
    execute(self.server.app)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 185, in execute
    write(data)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 153, in write
    self.send_header(key, value)
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 401, in send_header
    self.wfile.write("%s: %s\r\n" % (keyword, value))
IOError: [Errno 32] Broken pipe

你能为此建议解决这个问题吗?

谢谢,

3 个答案:

答案 0 :(得分:1)

根据烧瓶文档,使用@app.route修饰的函数不会使用url参数。这解释了你得到的错误。

看起来你还需要做

from flask import request

以便您可以在您的函数中访问请求。见这里:http://flask.pocoo.org/docs/0.10/quickstart/#the-request-object

执行此操作后,您可以根据此处的文档http://flask.pocoo.org/docs/0.10/api/#incoming-request-data

访问ajax调用发送的数据/查询参数

答案 1 :(得分:0)

上述错误堆栈跟踪是由跨区域调用引起的。实施CORS解决了这个问题。 最终工作守则:

Javascript代码:

function buttonClick() {
    makeCorsRequest('google.com');
}

// Create the XHR object.
function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        // XHR for Chrome/Firefox/Opera/Safari.
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
        // XDomainRequest for IE.
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        // CORS not supported.
        xhr = null;
    }
    return xhr;
}

// Make the actual CORS request.
function makeCorsRequest(url) {
    var tempURL = "http://127.0.0.1:5000/get_result/" + url
    var xhr = createCORSRequest('GET', tempURL);
    if (!xhr) {
        alert('CORS not supported');
        return;
    }

    // Response handlers.
    xhr.onload = function() {
        var text = xhr.responseText;
        alert('Response from CORS request to ' + url + ': ' + text);
    };

    xhr.onerror = function() {
        alert('Oops, there was an error making the request.');
    };

    xhr.send();
}

Python代码:

import flask
from flask import Flask
app = Flask(__name__)

@app.route("/get_result/<url>", methods=['GET', 'POST'])
def get_result(url):
    return "Hello World"

@app.after_request
def add_cors(resp):
    """ Ensure all responses have the CORS headers. This ensures any failures are also accessible
        by the client. """
    resp.headers['Access-Control-Allow-Origin'] = flask.request.headers.get('Origin', '*')
    resp.headers['Access-Control-Allow-Credentials'] = 'true'
    resp.headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS, GET'
    resp.headers['Access-Control-Allow-Headers'] = flask.request.headers.get(
        'Access-Control-Request-Headers', 'Authorization')
    # set low for debugging
    if app.debug:
        resp.headers['Access-Control-Max-Age'] = '1'
    return resp


if __name__ == "__main__":
    app.run(debug = True)

答案 2 :(得分:-1)

修订代码:Ajax Call(Javascript):

$.ajax({
    type: 'GET',
    url: "http://127.0.0.1:5000/get_result/google.com",
    data: {field: input.value}, //passing some input here
    dataType: "text",
    success: function(response) {
        output.value = response;
        alert(response);
    }
}).done(function(data){
        console.log(data);
});

Python代码:

from flask import Flask
app = Flask(__name__)

@app.route("/get_result/<url>", methods=['GET', 'POST'])
def get_result(url):
    return "Hello World"

if __name__ == "__main__":
    app.run(debug = True)