Django 对 Jquery $.ajax() 没有响应

0 投票
1 回答
661 浏览
提问于 2025-04-16 12:14

我在尝试向Django视图发送数据时遇到了一个大问题,因为它总是没有任何反应。

这是我的JQUERY代码:

$(function(){
   $("#sumbit_run").click(function(){
   $('#run-progress-bar').show('slow');
   $.ajax({
      type: 'POST',
      url: '/execute/run/',
      data: $('#form_run').serialize()+'&generation='+$('#generation').val()+'&size_population='+$('#size_population').val(),
      beforeSend: beforeRun,
      success: successRun,
      dataType: "xml"
    });
}); 

 function beforeRun(){
        if($('#mutation').val() !='' &&
 $('#crossover').val() !='' &&
 $('#size_population').val() !='fail'
 && $('#generation').val() !='' &&
 $('tuning').val() !='fail'){
            $('#run-progress-bar').show('slow');
            return true;        }else{
            $('#frmstatus').append("<p><strong>"+
 ERROR_EMPTY +"</strong></p>");
            $('#frmstatus').fadeOut(1500).fadeIn(1500).fadeOut(1100).fadeIn(1100).fadeOut(3000);
            return false;       
  }   
 }

function successRun(){
    $('#run-progress-bar').hide('slow');
    $('#list_results').empty();
    var id=0;
    $.getJSON('/execute/list_results/',function(data){
      $.each(data,function(key,value){
      id++;
           $('#result').append('<li><input type="checkbox" name="result" value="'+ value +'"><label id="__result" style="cursor: pointer; font-size:16px;" for="'+value+'">Trabajo # '+id+'</label></li>');
      });
      $('#__result').tooltip({
          track: true,
          delay: 0,
          showURL: false,
          showBody: " - ",
          extraClass: "pretty",
          fixPNG: true,
          opacity: 0.95,
          left: -120,
          bodyHandler: function() {
                return $($(this).attr('for')).html();
          },
      });
    });

这是我的HTML代码:

<form action="./" name="form_run" id="form_run" class="row" method="POST" enctype="multipart/form-data" >
<div style='display:none;'>
<input type='hidden' id='csrfmiddlewaretoken' name='csrfmiddlewaretoken' value='b8d81c090e88c2980c2397b00d720f0e' /></div>                 

<div id="file_selected"> 
  <label>File Seleccted</label> 
  <ul><input type="radio" id="a2.cnf" name="cnffiles" value="a2.cnf" selected='selected' style="cursor: pointer">a2.cnf</ul> 
</div> 
  <br /> 

  <label for="mutation">Mutacion</label> 
      <input type="text" id="mutation" name="mutation" maxlength="3" size="3" class="input_box" /> %
  <label for="crossover" style="padding-left:20px">Crossover</label> 
      <input type="text" id="crossover" name="crossover" maxlength="3" size="3" class="input_box" /> %
  <br /> 
  <label for="size_population"> Size of population</label> 
  <select id="size_population" name="size_population" class="input_box"> 
        <option value="half">Half</option> 
        <option value="normal" selected="true">Normal</option> 
        <option value="double">Double</option> 
  </select> 
  <br /> 
  <label for="generation">Number of Generations</label> 
      <input type="text" id="generation" name="generation" maxlength="5" size="6" class="input_box" /> 
  <br /> 
  <label for="tuning">Tuning</label> 
  <select id="tuning" name='tuning' class="input_box"> 
        <option value="fail">select</option> 
        <option value="mut_and_cross">mutation and crossover</option> 
        <option value="size_of_population">size of population</option> 
        <option value="size_of_generation">size of generation</option> 
  </select> 
  <br /> 
 <div id="frmstatus" class="error" style="display:none" ></div> 
      <input type="submit" id="sumbit_run" value="Enviar trabajo" class="input_box finger" style="font-size:20px; padding:10px;" /> 
 </form> 
 <div><span id="run-progress-bar" style="display: none;"><img src="/media/images/loader.gif" /></span></div> 

这是我的Django视图代码:

import os
# -*- coding: utf8 -*-
from django.core.context_processors import csrf
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.middleware.csrf import get_token
from execute.models import py_results
from django.utils import simplejson
from execute.pygenetics import *

def running(request):
    tuning=request.POST['tuning']
    name_file=request.POST['cnffiles']
    path = os.path.join('/home/paridin/public_html/pyGenetics/media/cnfs/',name_file) #send me and error i dont why
    pi = Genetic()
    pi.i_time = time.time()
    sat = SAT()
    index=[]
    population=[]
    desition=''
    GENERATION=request.POST['generation']
    i=0
    rang=[]
    [ob, sol] = sat.parser(path) 
    type_pop = request.POST['size_population']
    if type_pop == 'half':
        size_row = ob[0]/2
    elif type_pop == 'double':
        size_row = ob[0]*2
    else:
        size_row = ob[0]
    size_col = ob[0]
    index.append(random.randint(0,size_row-1))
    index.append(random.randint(0,size_row-1))
    rang.append(request.POST['mutation']) 
    rang.append(request.POST['crossover']) 
    population=pi.start_population(size_row,size_col) 
    status=pi.calculate_fitness(population,sol)
    old_population=population
    population=[]
    population=pi.new_population(old_population,rang,index,size_row)
    status=pi.calculate_fitness(population,sol)

    while(i<GENERATION):
        index[0]=random.randint(0,size_row-1)
        index[1]=random.randint(0,size_row-1)
        old_population=population
        population=[]
        population=pi.new_population(old_population,rang,index,size_row)
        status=pi.calculate_fitness(population,sol)
        if status=="update":
            pi.id = i
        i=i+1
    pi.e_time = time.time()
    u = py_results()

    try:
        result = py_results(
        user=u.get_user(2),
        time=str(pi.e_time-pi.i_time),
        best_time=str(pi.best_time),
        generation_id=pi.id,
        best_fitness=pi.fitness,
        type_tuning=tuning,
        mut_percent=rang[0],
        cross_percent=rang[1],
        num_gen=i,
        name_file=name_file, )
        result.save()
    except:
        return HttpResponse('ERROR NOT CAN INSERT IN DB')
    return HttpResponse('Save')

有趣的是,如果我把视图的完整路径放进去,就不会出现语法错误,但依然没有任何反应。

path = '/home/paridin/public_html/pyGenetics/media/cnfs/file.cnf'

我尝试用Debug工具0.8.4进行调试,但也没有任何效果。

使用Firebug时,提交表单后显示“待处理”,但也没有任何反应。

我尝试在Django中运行的pygenetics.py这个类,结果也没有任何反应,

但我在服务器上运行这个类时,一切都正常。

你能帮我吗?有没有什么想法为什么会这样?

相关问题:

1 个回答

0

好的,现在我知道问题出在哪里了。经过思考,我发现POST请求是一个字符串,所以当我开始执行“while”循环时,它永远不会结束,因为“i”是一个整数,而“GENERATION”是一个字符串。

那么,如何解决这个问题呢?

修复方法是:

GENERATION=(request.POST['generation'])

改成:

GENERATION=(int(request.POST['generation']))

然后:

rang.append(request.POST['mutation']) 
rang.append(request.POST['crossover']) 

改成:

rang.append(int(request.POST['mutation'])) 
rang.append(int(request.POST['crossover']))

再:

path=os.path.join('/home/paridin/public_html/pyGenetics/media/cnf',name_file)

改成:

path='/home/paridin/public_html_/pyGenetics/media/cnfs/%s' % request.POST['cnffiles']

现在一切都正常了。

希望这能帮助到其他人,祝你们的项目顺利 :-D

撰写回答