前端框架django; 后端语言python3
1、前后端关联
url.py (urlpatterns :path指定html、A方法)--->view.py (定义A方法)--->HTML(定义表单及返回位置)
url.py:
urlpatterns = [
path('web/', views.test),
view.py:
def test(request):
query = request.GET.get('q','') #request.GET是一个类字典对象,它包含所有GET请求的参数,这里表示取得name为'q'的参数值
html:
定义表单:
{% if result %}
{{ result }}
背景:从输入框输入数据,点击按钮,展示在指定文本框
url.py:
1)
path('pvs/',views.pvs)
2)
#增加一个路径:
url('pvs/kkk', views.kkk),
view.py:
1)
def test(request):
data = {}
if request.method == 'POST':
result = request.POST.get("tel")
print (result)
data = {"tel": result}
return HttpResponse(json.dumps(data))
return render_to_response('pvs.html',{"aaa":json.dumps(data)})
(#代替写法: return render(request, 'pvs.html')
2)
#增加一个方法:
def kkk(request):
data = {}
if request.method == 'POST':
result = request.POST.get("tel")
print (result)
data = {"tel": result}
return JsonResponse(data) #jsonresponse 需要 import
html:
var tel= document.getElementById('memid').value
$.ajax({
type: "POST",
data: {tel: tel},
url: "/pvs/", //后台处理函数的url 这里用的是static url 需要与urls.py中的name一致
2) url:"/pvs/kkk/" #第二种获取方式
dataType:'json',
success: function (result) {
$("#text").val(result.telvalue);
},
error: function () {
//alert("false");
document.getElementById("text").value = "未连接成功服务器";
}
})
参考:https://www.cnblogs.com/psklf/archive/2016/05/30/5542612.html
1、request.POST.("tel") 报错,request.POST.get("tel")正常
原因:
request.POST['sth']
will raise a KeyError
exception if 'sth'
is not in request.POST
.
request.POST.get('sth')
will return None
if 'sth'
is not in request.POST
. (有返回)
Additionally, .get
allows you to provide an additional parameter of a default value which is returned if the key is not in the dictionary. For example, request.POST.get('sth', 'mydefaultvalue')
This is the behavior of any python dictionary and is not specific to request.POST
.