2017-06-14 11 views
3

私は複数の入力タグを持っています。私の仕事は、ユーザーが入力した値を収集してサーバーに送り返すことです。私はフレームワークとしてDjangoを使用しています。私はクライアント側(javascript)にデータを送信するのに成功しています。 javascript関数からPython関数にデータを返すために、私はXMLHttpRequestを使いました。 私は以下の私のコードを追加しました:javascriptからpythonサーバーに値を送信しようとしています

<html> 
<head> 
<style>label{ text-align:center; width:250px; color:blue; display:inline-block}</style> 
<script type="text/javascript" src="'+url_read+'"></script> 
<script> 
function submit_this() 
{ 
var i,j;var arr=[]; 
for(i=0; i<Hello.length; i++) 
{ 
arr[i]=[]; 
for(j=0;j<Hello[i].length; j++) 
{ 
arr[i].push(document.getElementById(Hello[i][j]).value); 
} 
} 
alert(document.getElementById(Hello[1][0]).value); 
xmlHttpReq =  new XMLHttpRequest(); 
xmlHttpReq.open('POST', '/button_click',true);  
xmlHttpReq.send('w=' + encodeURI(arr)); 
} 
</script> 
</head> 
<body> 
<center> 
<button id="submit_button" onclick="submit_this();" value="Submit">Submit</button> 
</center> 
</body> 
</html> 

上記のコードはhtml_stringと呼ばれる文字列に格納されます。 こんにちは、varible url_readで示されるファイルから読み込まれたjsonオブジェクトです。 Pythonを使用してダンプされました。 HttpResponseを使用してhtml_stringを送信し、htmlページをレンダリングする予定でした。

私は、views.pyのいずれかのクラスで1つのPOST関数を作成する必要があることを理解しています。しかし、どのようにこの問題に近づくのか理解できません。

私は何とかサーバー側にarrという名前のjavascriptデータ構造を送信する必要があります。主な疑問は、javascript関数によって投稿された値をどこで読むことができるのか、私のコードをどこに置くことができるかです。 Djangoでは、各urlに(view.pyの)新しい関数が関連付けられているので、Submitボタンを押すと新しいページに移動します。私はそれを置くべきでしょうか?

+1

コードをフォーマットしてください。あなたのjsには、 – Ravi

+0

のタイプミス。 'xmlHttpReq.open( 'POST'、 '/ button_click'、true);' –

+0

あなたのコードには 'Hello'が入ります。他の場所で宣言されていますか?これがjsなどのキーワードかどうか疑問に思っています...? – Haranadh

答えて

0

ここでは、JSを使用して(Django)Pythonサーバーに値を送信し、HTMLレンダリングされたテンプレートを受け取る例を示します。 id #Nearbyのulタグを使用して、htmlをHTML内に読み込みます。 Ajaxの成功は、URLエンドポイント '/ getGopoints /'

template.html

<div class="row"> 
    <div> 
     <ul id="Nearby"> 

     </ul> 
    </div> 
</div> 

<script> 
$(document).ready(function(){ 
      $('#dataTables-example1').DataTable({ 
        responsive: true 
      }); 
      getLocation(); 
    }); 
function getLocation() { 
     if (navigator.geolocation) { 
      navigator.geolocation.getCurrentPosition(showPosition); 
     } 
    } 


function showPosition(position) { 
     $.ajax({ 
       url : '/getGopoints/', // the endpoint 
       type : 'GET', // http method 
       data : { 'lat' : position.coords.latitude, 
         'lon' : position.coords.longitude, 
         'csrfmiddlewaretoken': '{{csrf_token}}' 
       }, // data sent with the post request 

       // handle a successful response 
       success : function(data) { 
        $('#Nearby').html(data); 
       }, 
       dataType: 'html' 

     }); 
    } 
</script> 

urls.py

url(r'^getGopoints/$',views.getGopoints, name='getGopoints'), 

views.pyによってレンダリングされたDjangoのビューからHTMLを返します

def getGopoints(request): 
    lat = str(request.GET['lat']) 
    lon = str(request.GET['lon']) 
    pnt=fromstr('POINT(%s %s)' %(lon,lat)) 
    with_in_distance = 20 
    go_points = GoPoint.objects.filter(point__distance_lte=(pnt, D(km=with_in_distance))) 
    context = RequestContext(request, 
     {'go_points':go_points, 
     'with_in_distance':with_in_distance, 
     }) 
    return render_to_response('nearby.html', 
          context_instance=context) 
関連する問題