![](/img/trans.png)
[英]Unable to POST JSON object from Javascript to a Servlet via AJAX
[英]Unable to POST via JSON
我試圖將用戶文本從網頁發送到我的flask應用程序,以對用戶文本運行腳本,然后返回結果。 我遇到的問題是該文本未出現在服務器(flask_app.py)一側。 這是應該發送文本的.js文件(index.js):
$(document).ready(function(){
console.log('I have loaded');
//Grab DOM elements to use later
analyzeTextButton = $("#analyze-button");
analyzeTextButton.click(function() {
// get text
text = $("#user-text").val();
//console.log(text); //This part works
$.ajax({
type: "POST",
url: "analyze",
dataType: "json",
data: {
text
},
success: function(results, results2, verbs) {
text = results.text;
console.log("Success!");
console.log(verbs);
}
})
})
這是試圖接收它的Flask應用程序。 我嘗試了幾種不同的版本(來自其他Stack Overflow問題和各種教程),但是它們都不起作用。 它們被標記為content1-5。
flask_app.py:
@app.route('/analyze', methods=['POST'])
def analyze():
print('You made it to analyze', file=sys.stderr) #This gets printed
content = request.get_json(silent=True)
content2 = request.json
content3 = request.get_json()
content4 = request.form.get('html', '')
content5 = request.form['contents']
print(content, file=sys.stderr) #These all return "None"
print(content2, file=sys.stderr) #Trying to make them return user text
print(content3, file=sys.stderr)
print(content4, file=sys.stderr)
print(content5, file=sys.stderr)
text = "The text is not being found"
results = my_script(content) #Run a script on whichever works
return jsonify({'results': results})
這是試圖發送信息的頁面(index.html):
<div class="row">
<form role="form" method='POST' action='#'>
<textarea class="form-control" id="user-text" name="contents" placeholder="Enter a comment"></textarea>
<button type="button" id="analyze-button" class="btn btn-default">Not Working Button</button>
<button type="submit" id="analyze-button2" class="btn btn-default">Working Button</button>
</form>
編輯:當我在瀏覽器中查看時,我看到POST似乎正在發送正確的字符串:“ here + is + my + text”
data: {
text
}
應該是正確的JSON,應該是類似
data: {
"value":text
}
其中value
是鍵,文本變量是值。
該請求需要指定文本為html:
$.ajax({
type: 'POST',
url: "analyze",
data: {html:text},
dataType: 'json',
success: function (ret) {
alert('JSON posted: ' + JSON.stringify(ret));
}
});
在flask應用程序上,可以通過以下行讀取請求:
content4 = request.form.get('html', '')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.