Ajax JS

Ajax

AJAX 最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。

AJAX 不需要任何浏览器插件,但需要用户允许JavaScript在浏览器上执行。

  • ajax(本质;推荐)

      $.ajax({
          url: "/test_ajax",
          type: 'POST',
          // data: {'k1': 123, 'k2': 'aa},
      	data: $('#add_form').serialize(), 	# form表单打包发给服务器端
      	// data是服务器端返回的字符串
          success: function(data){
      		var obj = JSON.parse(data);
            	.....
          }
      })
    
  • $.get(url='xx', data={}, success=xxx)

    • 实际调用ajax,type为get
  • $.getJson

  • $.post

    • 实际调用ajax,type为post
  • app的views.py

    • return HttpResponse(json.dumps(字典)) # 推荐
    • return render(xxx) # 仅能返回对象类型,例如字典、列表、元组
    • return redirect(xxx) # 不用,用了也没效果,ajax不刷新

举例1

html文件
	<a id="ajax_submit" >悄悄提交</a>
	<input id="host" type="text" placeholder="主机名" name="hostname" />

	<script>
		$('#ajax_submit').click(function(){
                $.ajax({
                    url: "/test_ajax",
                    type: 'POST',
                    // data: {'hostname': $('#host').val(), 'ip': $('#ip').val(), 'port': $('#port').val(), 'b_id': $('#sel').val()},
					data: $('#add_form').serialize(),
                    success: function(data){
                       if (data == 'OK'){
                           location.reload() 
                       }else{
                           alert(data)
                       }
                    }
                })
         });
	</script>

工程中urls.py
	url(r'^test_ajax$', views.test_ajax),

app中的views.py
	def test_ajax(request):
	    h = request.POST.get('hostname')
	    i = request.POST.get('ip')
	    p = request.POST.get('port')
	    b = request.POST.get('b_id')
	    if h and len(h) > 5:
	        models.Host.objects.create(hostname=h,
	                                   ip=i,
	                                   port=p,
	                                   b_id=b)
	        return HttpResponse('OK')
	    else:
	        return HttpResponse("太短了")

缺陷:数据类型错误,用户不感知	

举例1:(改善)

html文件
	<span id="erro_msg" style="color: red"></span>

	<script>
		$('#ajax_submit').click(function(){
                $.ajax({
                    url: "/test_ajax",
                    type: 'POST',
                    // data: {'hostname': $('#host').val(), 'ip': $('#ip').val(), 'port': $('#port').val(), 'b_id': $('#sel').val()},
					data: $('#add_form').serialize(),
                    success: function(data){
                       var obj = JSON.parse(data);
                        if(obj.status){
                            location.reload();
                        }else{
                            $('#erro_msg').text(obj.error);
                        }
                    }
                })
         });	
    </script>

app中的views.py
	def test_ajax(request):
	    ret = {'status': True, 'error': None, 'data': None}
	    try:
	        h = request.POST.get('hostname')
	        i = request.POST.get('ip')
	        p = request.POST.get('port')
	        b = request.POST.get('b_id')
	        if h and len(h) > 5:
	            models.Host.objects.create(hostname=h, ip=i, port=p, b_id=b)
	        else:
	            ret['status'] = False
	            ret['error'] = "太短了"
	    except Exception as e:
	        ret['status'] = False
	        ret['error'] = '请求错误'
	    return HttpResponse(json.dumps(ret))

JS

  • 字符串转对象

    var obj = JSON.parse(data);

  • 对象转字符串

    JSON.stringify([1,2, 3])

  • json对象,通过点操作

  • 页面刷新

    location.reload();

  • 获取对象值

    $('#edit_form').find('select').val();

  • 设置对象值

    $('#edit_form').find('select').val("4");

    $('#edit_form').find('select').val(1);

  • 绑定事件

    • class

        <tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
        	<td>
        		<a class="edit">编辑</a>|<a class="delete">删除</a>
        	</td>
        </tr>
        
        <script>
         	$('.edit').click(function(){
                $('.shade,.edit-modal').removeClass('hide');
        
                var bid = $(this).parent().parent().attr('bid');
                var nid = $(this).parent().parent().attr('hid');
        
                $('#edit_form').find('select').val(bid);
                $('#edit_form').find('input[name="nid"]').val(nid);
        	})
        </script>
      
    • id

        <a id="ajax_submit" >悄悄提交</a>
      
        <script>
         $('#ajax_submit').click(function(){
        	....
         });
        </script>
      
    • 举例

        CSS
        	<style>
                .hide{
                    display: none;
                }
                .shade{
                    ....
                }
                .add-modal,.edit-modal{
                    ....
                }
            </style>
      
        html
        	<input id="add_host" type="button" value="添加" />
        	<div class="shade hide"></div>
            <div class="add-modal hide">
                <h3>添加主机信息</h3>
        	</div>
      
        JS
        	<script>
        		 $(function() {
                     $('#add_host').click(function () {
                         $('.shade,.add-modal').removeClass('hide');
                     });
        		 });
        	</script>
      
posted @ 2017-12-27 22:16  12兵哥哥  阅读(135)  评论(0编辑  收藏  举报