django:通过JQuery传递特定的表单数据

时间:2013-07-16 17:30:16

标签: django jquery

如何通过Django中的Jquery传递任何特定的表单值进行处理?我想通过JQuery将我的表单中标签'machine'的值传递给views.py。这是我的代码:

template.py:

<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">

$(document).ready(
                 function() {  

                    $("#submit").click(function (event) {
                        event.preventDefault();
                        var machine = $("#machine").val();    //taking the machine value
                        var data = { machineID: machine};     //data dictionary
                        var url = "/vsawebauto/automation/results/job_processing";
                        $.getJSON(url, data, function(machines) {
                                $("#progress").text(machines[0].fields['machine_name']);
                        });                            
                      });                           
});
</script>
</head>

<body>
<form name="resultsForm" method="post">
{% csrf_token %}

<br><label id="machine" value="{{ selected_machine }}">Selected Machine: {{ selected_machine }}</label></br>
<br><input type="submit" id="submit" value="Submit Job" /></br>
<br><div class="progress" id="progress"></div></br>
</form>
</body>
</html>

views.py

def job_processing(request):
    machineID = request.POST.get('machineID', False)
    machine = Client.objects.get(pk=machineID)
    isAutomationPkgCopySuccessful = JobRunner.copyAutomationPackage(machine.machine_name,machine.username,machine.password,request)
    availableMachines = runningProcess.ParseMachineList(request)
    json_models = serializers.serialize("json", availableMachines)
    return HttpResponse(json_models, mimetype="application/javascript; charset=UTF-8") 

当我调试代码时,views.py中的machineID的布尔值为'False'(它的值应为 $(“#machine”)。val()从templates.py传递这是'1')

1 个答案:

答案 0 :(得分:2)

对于初学者,您使用$ .getJSON,然后在request.POST

中查找machineID

你应该使用request.GET.get('machineID', False)

其次,我想你的表单将通过POST提交,总是没有必要在提交按钮上附加点击事件。

<script type="text/javascript">
$(document).ready(function() {
$("#myform").submit(function(event){
    event.preventDefault(); 
    var machine = $("#machine").val();
    var data = { machineID: machine};
    var url = "/vsawebauto/automation/results/job_processing";
    $.getJSON(url, data, function(machines) {
       $("#progress").text(machines[0].fields['machine_name']);
    });  
});
</script>

<form id="myform">
  <br><label id="machine" value="{{ selected_machine }}">Selected Machine: {{ selected_machine }}</label></br>
  <br><input type="submit" name="submit" value="Submit"> < /br>
  <br><div class="progress" id="progress"></div></br>
</form>