我想从python服务器发送一个结果作为对客户端JavaScript的响应。 我的JavaScript代码在这里:
document.addEventListener('DOMContentLoaded', function() {
chrome.tabs.getSelected(null, function(tab) {
d = document;
var xhr = new XMLHttpRequest();
var f = d.createElement('form');
f.action = 'http://127.0.0.1:5000/Get%20Form/';
f.method = 'post';
var i = d.createElement('input');
i.type = 'hidden';
i.name = 'url';
i.value = tab.url;
f.appendChild(i);
d.body.appendChild(f);
f.submit();
});
}, false);
还有我的python服务器代码如下:
from django.http import HttpResponse
import json
from flask import Flask, flash, redirect, url_for, request,
render_template,jsonify
app = Flask(__name__)
user=""@app.route('/Get Form/',methods = ['POST'])
def GetForm():`
request.method == 'POST'
url=request.form['url']
print url
data={}
data['url'] = url
data['result'] = 'safe'
response = HttpResponse(json.dumps(data), content_type = "application/json")
print response
return
if (__name__ == '__main__'):
app.run(debug=True,host='0.0.0.0', use_reloader=False)
任何正文帮助我将JSON对象响应发送到客户端JavaScript
答案 0 :(得分:0)
您可以在问题
的代码中使用FormData()
XMLHttpRequest()
变量xhr
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://127.0.0.1:5000/Get%20Form/");
xhr.onload = function() {
console.log(xhr.responseText) // do stuff with response from server
}
xhr.onerror = function(err) {
console.error(err)
}
var fd = new FormData();
fd.append("url", tab.url);
xhr.send(fd);