Django не отвечает JQuery $ .ajax () - PullRequest
0 голосов
/ 22 февраля 2011

У меня большая проблема, когда я пытаюсь отправить данные в представление 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 VIEW CODE

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'

попытка отладкис панелью отладки 0.8.4, но никогда ничего не делает,

с firebug отправил мне сообщение «Ожидание» после отправки формы и никогда ничего не делает.

Вызов класса pygenetics.pyя пытаюсь запустить в Django и никогда ничего не делаю, я запускаю этот класс на сервер, и все работает хорошо.

Вы можете мне помочь?есть идеи, почему так происходит?

1 Ответ

0 голосов
/ 22 февраля 2011

Хорошо, теперь я знаю, в чем проблема, после того, как подумать, почему ?, я обнаружил, что запрос 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...