2014-11-24 2 views
2

이 같은 일부 코드가 있습니다자바 스크립트 함수의 값을 장고보기에 전달하는 방법은 무엇입니까? 템플릿에서

<div id="form"> 
     <form name="myForm" action="Http://localhost:8000/student/student_add_course/" onclick="return addTable();" method="post"> 
     {% csrf_token %} 
     {{ form.non_field_errors }} 
       <div id="form-data"> 
       {{ form.course_id }}{{ form.course_id.errors }} 
       <label for="id_course_id">:Course Id number:</label><br> 

       {{ form.score }}{{ form.score.errors }} 
       <label for="id_score">Course score:</label><br> 
       <p><input type="button" value="add" /></p> 
       <p><input type="submit" value="submit" /></p> 
       </div> 
     </form> 
    </div> 

    <div id="table"> 
    <table id="TABLE" border = '1'> 
    <tr> 
     <th>id number</th> 
     <th>score</th> 
    </tr> 
    <tr> 
     <td id="id_number"></td> 
     <td id="score"></td> 
    </tr> 

을 그리고 이것은 "스크립트"일부입니다

<script type="text/javascript"> 
    var stock = new Array(); 
    var i = 0; 

    function addTable() { 

     var id = document.forms["myForm"]["course_id"].value; 
     var score = document.forms["myForm"]["score"].value; 

     stock[i] = new Array(id, score); 

     //Get the table that shows the selected course from html code 
     var table = document.getElementById('TABLE'); 

     //Add id and score to row of the table which is inside the html code. 
     if (document.getElementById("id_number").innerHTML=="" || document.getElementById("score").innerHTML=="") 
      {document.getElementById("id_number").innerHTML=id; 
      document.getElementById("score").innerHTML=score;} 

     //Create table row and append it to end of above table 
     else{var tr = document.createElement('TR'); 
      for (j = 0; j < 2; j++) { 
       var td = document.createElement('TD') 
       td.appendChild(document.createTextNode(stock[i][j])); 
       tr.appendChild(td) 
       } 
      table.appendChild(tr); 
      } 

     i=i+1; 
     return stock; 
    } 

</script> 

내가 선택한 학생을위한 새로운 과정을 추가하고 싶은 그 일을 위해, 내가 만들 양식 번호와 코스 점수를 얻는 폼. 처음에는 양식을 채울 때 "추가"버튼을 클릭하면 자바 스크립트가 테이블을 만들고 많은 과정을 추가 할 수 있습니다. 그러면 뷰 부분의 다른 단계를 수행하고 모두 저장해야합니다. 물론 데이터베이스에. 몇 가지 문제가 있습니다. 제가 도움이된다면 행복 할 것입니다.

1) Django 뷰에 "stock"배열 (자바 스크립트에서 전역 배열이며 생성 된 테이블의 모든 코스 포함)을 보내는 방법은 무엇입니까?

2) "추가"버튼을 누른 후 얼마나 깨끗한 형태입니까?

나쁜 영어로 유감입니다.

+0

이 http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp 또는 jqery 아약스 http://api.jquery.com/jquery.ajax/ – madzohan

+0

를 사용하여 AJAX 노력이되기를 바랍니다! 더 많은 정보는 여기 : http://stackoverflow.com/questions/20306981/how-do-i-integrate-ajax-with-django-applications – seddonym

답변

1

안녕하세요, 데이터를 다시 보내려면 POST 요청을 다시 서버로 보내야합니다. (이 훨씬 빠르고 쉽게 때문에) 당신의 postendpoint 및 지점에 맞게 앱의 urls.py를 조정

$.ajax({ 
    // points to the url where your data will be posted 
    url:'/postendpoint/$', 
    // post for security reason 
    type: "POST", 
    // data that you will like to return 
    data: {stock : stock}, 
    // what to do when the call is success 
    success:function(response){}, 
    // what to do when the call is complete (you can right your clean from code here) 
    complete:function(){}, 
    // what to do when there is an error 
    error:function (xhr, textStatus, thrownError){} 
}); 

그런 다음 당신이해야합니다 그렇게 예를 들어 JQuery와 사용하려고

임 예를

마지막으로
##urls.py 
urlpatterns = [ 
    url(r'^postendpoint/$', views.YourViewsHere), 
    .... 
] 

하고보기에이

##views.py 
def YourViewsHere(request): 
    if request.method == 'GET': 
     do_something() 
    elif request.method == 'POST': 
     ## access you data by playing around with the request.POST object 
     request.POST.get('data') 
같은 포스트 데이터에 액세스 할 수 있습니다에 대한 올바른보기에 그것은

요청할 수있는 python 개체는 많은 특성과 메서드를 볼 수 있습니다. 당신은 내가 준 코드와 함께 놀러해야합니다 How do I integrate Ajax with Django applications?

주 : 추가 정보를 위해

1) 장고 요청 - 응답 https://docs.djangoproject.com/en/1.7/ref/request-response/ 2) 장고 아약스 부여 됨으로써 봐. 거기에서 배울 수있는 최선의 방법이라고 생각합니다.

난 당신이 유용

+0

답장을 보내 주셔서 감사합니다. 도움이된다고 생각하지만 JQuery와 처음에 나는 그것을 배워야한다고 생각합니다 :) 고마워요. – user3789719

+0

정답으로 내 대답을 수락 할 수 있습니까? 건배 =) – biobirdman

+0

JQuery를 사용하지 않고 게시물 호출에 vanilla javascript를 사용할 수 있지만 개념은 같습니다. 자바 스크립트에서 요청에 데이터를 추가하고 django에서 요청 객체에 액세스하여 데이터에 액세스해야합니다. – biobirdman

관련 문제