0

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

模板.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>

视图.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'(它应该具有从 templates.py 传递 的$("#machine").val()的值,即'1')

4

1 回答 1

2

For starters you are using $.getJSON and then looking for machineID in request.POST

you should use request.GET.get('machineID', False)

Secondly I would imagine your form will get submitted via POST always there is no point attaching a click event on the submit button.

<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>
于 2013-07-16T17:46:39.550 回答