.py ファイルから出力された Json オブジェクトを Jquery の getJson メソッドに送信しようとしていますが、何か問題が発生しています。動作していないコードを含む大きなプロジェクトからいくつかの簡単な例を作成しました。いくつかの助けをいただければ幸いです!
HTML ファイル:
<html xmlns=" http://www.w3.org/1999/xhtml ">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Request json test</title>
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script src="/js/json-jquery.js" type="text/javascript"></script>
</head>
<body>
<a href="#" id="getdata-button">Get JSON Data</a>
<div id="showdata"></div>
</body>
</html>
JS ファイル:
$(document).ready(function(){
$('#getdata-button').live('click', function(){
console.log("echo ")
$.getJSON("/js/getActive.py", function(data) {
console.log("echo "+ data)
$('#showdata').html("<p>item1="+data.item1+"</p>");
});
});
});
.py ファイル:
import json
impact="pedro"
print json.dumps({'item1': impact})
問題については、 $.getJSON 命令の下に何も出力されません。ブラウザで確認したところ、スクリプトが見つかり、http で OK ステータスになりました。何が起こっているのか本当にわかりません。それが明白なものである場合は申し訳ありませんが、あなたが与えるかもしれない助けを事前に感謝します.
json形式の行をいくつか尊重した.txtファイルでこれを試してみましたが、正常に動作します。
----------
更新: 解決策
私は Django を使用しているため、例とは少し異なる動作をするため、正しく考えていませんでした。ここに行きます。
JS ファイルは、views.py の関数にリダイレクトする URLs.py にある URL を呼び出す必要があります。
$(document).ready(function(){
//attach a jQuery live event to the button
$('#getdata-button').live('click', function(){
console.log("echo ")
$.getJSON("teste.html", function(data) {
console.log("echo "+ data)
//alert(data); //uncomment this for debug
//alert (data.item1+" "+data.item2+" "+data.item3); //further debug
$('#showdata').html("<p>teste="+data.item1+"</p>");
});
});
});
次に、views.py で必要な情報を処理し、JSON を使用して httpResponse を JS に戻してビューに処理します。
def teste(request):
to_json = {
"item1": "pedro"
}
return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')