經過ajax GET方式查詢數據,Django序列化objects

點擊「查找2」按鈕,經過ajax GET方式進行查詢數據,這樣頁面不須要總體刷新,以後清空tbody數據,將查詢結果從新附加到tbodyhtml

前端html:前端

<div class="box-header">
    <i class="icon-table"></i>
    <h5 id="resultcount"> 設備 (共計{{counts}}) </h5>
    <input  style="margin:10px" type="button" id='butupdate' name='Update' value="Update" class="btnc1" style="margin-left:5px;border-bottom: #93bee2 1px solid">
</div>
<div class="box-content box-table" id="tablec">
<div class="holder"></div>

<form id="searchform" action="" method="get" style="display:inline">
  {% csrf_token %}
    <input type="text" name="q" class="text-search" style="margin-left:42px;display:inline;width: 115px">

    <label style="margin-left:10px;display:inline">By</label>
    <select id="slctsrv" name="slctsrv" style="margin-left:5px;width: 120px">
        <option value="APP">應用</option>
        <option value="IP" selected="selected">IP</option>
        <option value="ServerName">名稱</option>
    </select>
    <input type="button" id="search2" value="查找2" class="btn" style="margin-left:5px">
</form>

前端js:ajax

$("#search2").on("click",function(){
     //查找每一個button所在行的td的值
    $.ajax({
        type: 'GET',
        //url: '/aptest/',
        data:$('#searchform').serialize(),
        dataType:'json',
        success:function(response,stutas,xhr){
           $('#servers tbody').empty(); //清空tbody內容
           $('#resultcount').empty();   //清空查詢個數
           $("#resultcount").append("設備 (共計" + response.length + ")"); //顯示查詢結果數量
           $.each(response,function(i,item){ //response爲返回結果,是一個array,而後對該array進行遍歷,fields屬性中包含全部查詢內容,pk爲每條結果的主鍵字段 var vfields = item.fields
            var _len=$("#servers tr").length;
            $("#servers tbody").append("<tr >" //id="+_len+" class='success'
                    +"<td width='2%'><input id='ckbid' name='ckb' type='checkbox'/></td>"
                    +"<td id='num'>"+_len+"</td>"
                    +"<td id='PKID' style='display:none'>" + item.pk +"</td>"
                    +"<td id='APP'>"+ vfields.APP +"</td>"
                    +"<td id='IP'>"+ vfields.IP +"</td>"
                    +"<td id='ServerName'>"+ vfields.ServerName +"</td>"
                    +"<td id='DomainName'>"+ vfields.DomainName +"</td>"
                    +"<td id='CPU'>"+ vfields.CPU +"</td>"
                    +"<td id='MemorySize'>"+ vfields.MemorySize +"</td>"
                    +"<td id='DISK'>"+ vfields.DISK +"</td>"
                    +"<td id='SN'>"+ vfields.SN +"</td>"
                    +"<td id='Type'>"+ vfields.Type +"</td>"
                    +"<td id='OSVersion'>"+ vfields.OSVersion +"</td>"
                    +"<td id='iDRAC'>"+ vfields.iDRAC +"</td>"
                    +"<td id='Rack'>"+ vfields.Rack +"</td>"
                    +"<td id='Person'>"+ vfields.Person +"</td>"
                    +"<td id='Person_app'>"+ vfields.Person_app +"</td>"
                    +"<td id='OS_mark'>" + vfields.OS_mark +"</td>"
                    +"<td><input type='button' id='bbt' value='保存' /></td>"
                    +"</tr>");
    $("#ttb").trigger("update"); //sorter
           })
        },
        error:function(xhr,errorText,errorStatus){
          alert(xhr.status+' error: '+xhr.statusText);
        },
        timeout:5000
    });
     
  });

 

編寫view(Django序列化objects):django

from django.core import serializers #導入serializers模塊
#查詢
if request.method == 'GET':
    if 'q' in request.GET:
        q=request.GET['q']
        if q is not None:
            filterconitionname = request.GET['slctsrv'] + '__icontains'
            srvs = serverinfors.objects.filter(**{filterconitionname:q})
            srvs_json = serializers.serialize("json",srvs)
            return HttpResponse(srvs_json) #將objects過濾結果序列化後返回給ajax接收,對於Jquery來講一個array

 print srvs_jsonjson

[{"fields": {"OSVersion": "CentOS", "APP": null,"OS_mark": "Linux"}, "model": "sinfors.serverinfors", "pk": 178}]app

print type(srvs_json) 返回值:‘unicode’url

對srvs_json反序列化:spa

from django.core.serializers import serialize,deserialize
deserialize('json',srvs_json) # 返回值是一個迭代器,以下:
>> <generator object Deserializer at 0x00000000036A65A0>
#查看每一個結果:
for i in deserialize('json',sj):print i.object.APP

 

去掉先後[],方法:srvs_json[1:-1].net

django的 serializers 只支持 queryset,而不支持model的實例code

srvs = serverinfors.objects.get(pk=178)
data = serializers.serialize("json",srvs) 

錯誤提示:TypeError: 'serverinfors' object is not iterable

解決方式,添加[],以下:

serializers.serialize("json",[srvs])

 

參考:http://blog.csdn.net/woohyuknrg/article/details/17140531

相關文章
相關標籤/搜索