2017-12-04 10 views
-1

Pythonでアプリケーションを構築する方法については、flask tutorialに従っています。次のようにAJAXのpython内でJSONを掲載取得する方法についてAJAXにフラスコにJSONを投稿するには?

チュートリアル(終了間近の)会談:

HTMLコード:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> 
 
<script type="text/javascript"> 
 
// setup some JSON to use 
 
var cars = [ 
 
\t { "make":"Porsche", "model":"911S" }, 
 
\t { "make":"Mercedes-Benz", "model":"220SE" }, 
 
\t { "make":"Jaguar","model": "Mark VII" } 
 
]; 
 

 
window.onload = function() { 
 
\t // setup the button click 
 
\t document.getElementById("theButton").onclick = function() { 
 
\t \t doWork() 
 
\t }; 
 
} 
 

 
function doWork() { 
 
\t // ajax the JSON to the server 
 
\t $.post("receiver", cars, function(){ 
 

 
\t }); 
 
\t // stop link reloading the page 
 
event.preventDefault(); 
 
} 
 
</script> 
 
This will send data using AJAX to Python:<br /><br /> 
 
<a href="" id="theButton">Click Me</a>

Pythonのコード:

`import sys 

from flask import Flask, render_template, request, redirect, Response 
import random, json 

app = Flask(__name__) 

@app.route('/') 
def output(): 
    # serve index template 
    return render_template('index.html') 

@app.route('/receiver', methods = ['POST']) 
def worker(): 
    # read json + reply 
    data = request.get_json() 
    result = '' 


    for item in data: 
     # loop over every row 
     result += str(item['make']) + '\n' 

    return result 

if __name__ == '__main__': 
    # run! 
    app.run()` 

スクリプトを実行してブラウザの「Click me」ボタンをクリックすると、「500 Internal Se rver Error 'というエラーメッセージが表示されます。データ変数を出力すると、端末のClickイベントでNoneが出力されます。私は、pythonスクリプトでget_json(forced = true)を使用し、htmlファイルで 'cars' jsonをストリング化するためにコメントに与えられた提案を試みましたが、無駄でした。

答えて

0

それはあなたがあなたのポストの要求のコンテンツタイプを指定していないようin the official documentation言われているものを見になります。MIMEタイプは アプリケーション/ JSONでない場合は、デフォルトで

この機能はNoneを返しますが、これはforceパラメータでオーバーライドすることができます。

車オブジェクトをjsonオブジェクトにシリアライズする必要もあります。

function doWork() { 
    // ajax the JSON to the server 
    $.ajax({ 
    type: 'POST', 
    url: '/receiver', 
    data: JSON.stringify (cars), 
    success: function(data) { alert('data: ' + data); }, 
    contentType: "application/json", 
    dataType: 'json' 
}); 
    // stop link reloading the page 
event.preventDefault(); 
} 

あなたはこのような何かを行うことができます

関連する問題