2017年11月6日 星期一

JQuery - AJAX筆記

本筆記將實作JQuery AJAX + Django 按鈕觸發AJAX


# ajax.html

<!DOCTYPE html>
<html>
<head>
<title>Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>
  $( document ).ready(function() {
$("#btn1").on('click', function () {
$.ajax({
url: 'http://localhost:8000/basic_app/get_json_data/',
type: 'get',
data: {},
dataType: 'json',
timeout: 10000,
success: function(result) {
alert('sucess');
$('#txt1').html(result.result);
},
error: function() {
$('#txt1').html("error");
    }
});
});
});
</script>
</head>
<body>
<h1>Ajax</h1>
<h1 id="txt1" >ready</h1></br>
<button type="button" id="btn1">turn off </button>
</body>
</html>


# views

from django.http import HttpResponse
import json

def get_json_data(request):
    a = {
    'result' : 'success',
    }
    return HttpResponse(json.dumps(a), content_type='application/json')


# urls.py

url(r'^get_json_data/', views.get_json_data,name='get_json_data'),

完成

沒有留言:

張貼留言