2012-05-15 65 views
0

我有一個窗體,用於添加一個項目,其中2個下拉列表填充使用不同的數據庫比提交表單的數據庫。我想將AJAX添加到下拉列表中,在第一個下拉列表中選擇一個項目將自動使用AJAX填充第二個下拉列表中的數據。問題是我使用相同的視圖來填充數據,即使使用is.ajax()調用,它也不能工作。Django使用AJAX與窗體,視圖

這裏是我的AJAX代碼:

function get_data(){ 
// alert('test'); 
new Ajax.Request('/abc/abc/add', { 
method: 'POST', 
parameters: $H({'type':$('id_data').getValue()}, 
          {'csrfmiddlewaretoken':$("csrfmiddlewaretoken").getValue()}), 
onSuccess: function(transport) { 
    var e = $('id_def') 
    if(transport.responseText) 
     e.update(transport.responseText) 
} 
}); // end new Ajax.Request 
//alert($("csrfmiddlewaretoken").getValue()); 
} 

這裏是我的視圖代碼:

if request.is_ajax(): 
#if request.is_ajax() 
    cur = connections['data'].cursor() 
    #auto_type = Auto.objects.filter(type=request.POST.get('type', '')) 
    abctype = request.POST.get('type', '') 
    SQL = 'SELECT uuid FROM abc_abc where uid = %s', abctype 
    cur.execute(SQL) 
    auto_type =cur.fetchone() 




    cur = connections['data'].cursor() 
    SQL = 'SELECT uuid, name FROM abc_abc where parent_id = %s', auto_type 
    cur.execute(SQL) 
    colors = cur.fetchall() 
    return render_to_response('abc/add_abc.html', { 
      'colors' : colors, 
      }, context_instance=RequestContext(request)) 

還有什麼是我米失蹤?請讓我知道,如果你想我從代碼中添加更多的東西.....請幫助!

+0

我已經和這似乎是工作。我在網上使用Ajax和Django的一個例子,並從那裏獲得了代碼。 http://bradmontgomery.net/blog/a-simple-django-example-with-ajax/ – us1415

+0

....我使用原型庫http://prototypejs.org/ – us1415

+0

是否有一個原因,你的原料返回HTML('abc/add_abc.html'),它沒有錯,但我期望json – josephmisiti

回答

0

我得到它的工作。似乎喜歡js文件我正在發送參數列表後的第二個參數。下面是新的代碼:

function get_data(){ 
new Ajax.Request('/abc/abc/add', { 
method: 'POST', 
parameters: $H({'type':$('id_data').getValue(), 
       'csrftoken':$("csrftoken").getValue() 
       }), 
onSuccess: function(transport) { 
var e = $('id_data1') 
if(transport.responseText) 
     e.update(transport.responseText) 
} 

}); // end new Ajax.Request 
} 

這是我的觀點:

if request.is_ajax(): 
    cur = connections['data'].cursor() 
    SQL = 'SELECT uuid, name FROM abc_abc where parent_id = %s' 
    auto_type = request.POST.get('type','') 
    conv = iri_to_uri(auto_type) 
    conv2 = (conv,) 
    cur.execute(SQL,conv2) 
    colors = dictfetchall(cur) 
    return render_to_response('abc/add.html', { 
      'colors' : colors, 
      }, context_instance=RequestContext(request)) 

下面是HTML obejct:

<table border="0" cellpadding="0" cellspacing="0"> 
     <tr>{{ form.abc.errors }}</tr> 
     <tr> 
      <th><label>ABC:</label></th> 
      <td><select name="abc" id="id_abc"> 
    <option value="" selected="selected">---------</option> 
{% for c in colors %} 
<option value="{{ c.uuid }}">{{ c.name }}</option> 
    {% endfor %} 
</select></td> 
      <td></td> 
     </tr> 
    </table> 
    <br>