前臺通過form表單向Django後臺傳輸資料,Django處理後返回給前臺
阿新 • • 發佈:2018-12-20
摘要:Django前後臺數據傳遞
通過action將資料傳輸給apitest這個地址,使用get方法傳遞,此處需要傳遞name="request_method"的下拉列表值和name="api_url"的輸入框的值,
注意這裡用name屬性,向Django後臺傳遞時需要用name的值作為鍵取對應的值
<!-- 這裡的action的值一定要/開頭,否則報錯 --> <form action="/apitest" method="get"> {# <label class="qwew">請求方法:</label>#} <div class="api-form" align="center" > <select class="api-method" name="request_method" > <option>GET</option> <option>POST</option>response </select> <input id="url-input"name="api_url" class="form-control" type="text" placeholder="輸入介面完整地址" value=""/> <input id="send-button" type="submit" value="傳送請求" /> </div> </form>
這個地址在路由中又對應了apitest這個檢視去處理資料,這兩處名稱一樣僅僅是巧合
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', views.index), url(r'^404/', views.notfound), url(r'^form_builder/', views.form_builder), url(r'^base/', views.base), url(r'^layouts/', views.layouts), url(r'^showcase/', views.showcase), url(r'^API_MASTER/', views.API_MASTER), url(r'^apitest/', views.apitest), ]
然後看檢視函式怎麼接收資料
get方法:
request_method = request.GET['request_method'] api_url = request.GET['api_url']
post方法:
request_method = request.POST['request_method']
api_url = request.POST['api_url']
def apitest(request): request_method = request.GET['request_method'] api_url = request.GET['api_url'] print request_method print api_url r = requests.get(api_url) print r.content return render(request, 'showcase/API_MASTER.html',{'response': r.content})
處理完成後需要將資料{'response': r.content}傳遞到前臺
使用 {{變數}} 方式獲取資料
<textarea id="response-body">{{ response }}</textarea>