python ajax post 数据
简单的html
<div> <input type="submit" id="tes" value="tes"> <div id="test"></div> </div>
简单的后台函数
def tes(request): url = request.POST[‘url‘] if ‘url‘ in request.POST else ‘t‘ word = request.POST[‘word‘] if ‘word‘ in request.POST else ‘t‘ return HttpResponse(url+word)
直接贴javascript
$(document).ready(function() {
//获取cookie函数 function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != ‘‘) { var cookies = document.cookie.split(‘;‘); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + ‘=‘)) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }
//获取csrftoken对应的cookie var csrftoken = getCookie(‘csrftoken‘); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }
#cookie写入头部 $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $("#tes").click(function() { // alert("t"); // $.get(‘http://127.0.0.1:8000/search‘, function(data) { // optional stuff to do after success // $("#test").append(data); // }); var csrftoken = $.post(‘tes/‘, { url:‘url‘, word:‘word‘, }, function(data, textStatus, xhr) { /*optional stuff to do after success */ $("#test").append(data); }); }); });
结果:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。