阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

高阶应用-Ajax

119次阅读
没有评论

共计 1099 个字符,预计需要花费 3 分钟才能阅读完成。

一、方法

is_ajax() 判断是否为 ajax 请求

二、Ajax GET 示例

  • 模板代码

    <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> function ajax_get() {$.get('/test_ajax/', function(data){console.log(data) }) } </script> </head> <body> <a href="#" onclick="ajax_get();">ajax_post</a> </body> </html>
  • 视图

    from django.http.response import JsonResponse def test_ajax(req): print(req.is_ajax()) return JsonResponse({'code': 200})
  • 路由地址

    urlpatterns = [path(r'', main.index, name='index'), path(r'test_ajax/', main.test_ajax, name='test_ajax'), ]

三、Ajax POST 示例

  • 模板代码

    <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> $.ajaxSetup({data: {csrfmiddlewaretoken: '{{csrf_token}}' }, }); function ajax_post() {$.post('/test_ajax/', function(data){console.log(data) }) } </script> </head> <body> <a href="#" onclick="ajax_post();">ajax_post</a> </body> </html>

    ajaxSetup() 方法为将来的 AJAX 请求设置默认值。

  • 视图函数

    from django.http.response import JsonResponse def test_ajax(req): print(req.is_ajax()) return JsonResponse({'code': 200})
  • 路由地址

    urlpatterns = [path(r'', main.index, name='index'), path(r'test_ajax/', main.test_ajax, name='test_ajax'), ]

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-05-26发表,共计1099字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中