jq ajax 小例子,django jquery ajax 的一个小例子

I

recently discovered a neat way of displaying data retrieved using

jquery AJAX in concert with Django’s template engine. You can create a

view in Django which simply uses the render_to_response shortcut function to render the results server-side and then just use jquery.load to dynamically fetch the results.

Eventhough, returning some raw JSON data is much more efficient as far as bandwidth is concerned, method is a lot simpler.

I have been using jquery for over a year now. I have found that its

built-in DOM manipulation features are a bit limited, especially for

manipulating tables (e.g., adding rows dynamically). This method is

much cleaner than doing all that DOM manipulation.

Here is all the jQuery code to handle the search and AJAX spinner display:

01.$( document ).ready(function() {

02.$('#searchSubmit' ).click(function() {

03.q = $('#q' ).val();

04.$('#results' ).html(' ' ).load(

05.'{% url demo_user_search %}?q=' + q );

06.});

07.});

08.

09.$( document ).ajaxStart(function() {

10.$('#spinner' ).show();

11.}).ajaxStop(function() {

12.$('#spinner' ).hide();

13.});

Here is the Django view function that does the heavy lifting on the server-side:

01.def ajax_user_search( request ):

02.if request.is_ajax():

03.q= request.GET.get('q' )

04.if qis not None:

05.results= User.objects.filter(

06.Q( first_name__contains= q ) |

07.Q( last_name__contains= q ) |

08.Q( username__contains= q ) ).order_by('username' )

09.

10.template= 'results.html'

11.data= {

12.'results': results,

13.}

14.return render_to_response( template, data,

15.context_instance= RequestContext( request ) )

Here are some screenshots of the results:

2_ajax1.png

AJAX operation in progress

3_results1.png

Returned results

1_noresults1.png

No results

The sample Django project is included for your perusal and is released under the MIT license. I used the excellent Aptana Studio IDE when working on this demo so it can be imported straight into it as an Aptana project.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值