最近遇到一個問題,前端表單我寫了多個按鈕,每個按鈕通過for循環來給name賦值如下:
<input type="button" class="btn btn-info btn-xs" name="{{item.document}}" value="解析" onclick="Parsefunc(this.name)">
問題是我想要實現點擊哪個按鈕就傳對應按鈕的值到後端,對於我這樣的前端新手就比較麻煩了。。。於是乎,各種詢問、谷歌...用了三天才發現原來實現出來那麼簡單,要被大神們嘲笑了,廢話少說,我用了ajax傳遞數據:
function Parsefunc(dataname){ // var dataname = $(this).attr('name'); // alert(dataname); $.ajax({ url:"/file_parse/", type:"POST", contentType: "application/json", data:JSON.stringify({ 'data':dataname }), success:function(response){ window.wxc.xcConfirm("成功", window.wxc.xcConfirm.typeEnum.success); }, error:function(response){ window.wxc.xcConfirm("失敗", window.wxc.xcConfirm.typeEnum.error); } }) }
在後端用了rest_framework
from rest_framework.decorators import api_view
@api_view(['GET', 'POST'])
def file_parse(request):
uploadfile_info = upload_document.objects.all()
if request.method == 'POST':
info = request.data.get('data')
inf = request.data
print(info)
print(inf)
context = {'uploadfile_info': uploadfile_info}
return render(request, 'logfile/file_parse.html', context)
成功,至少這個值是打印出來了,功能實現了,畢竟實現第一,改進第二,還得得慢慢磨練,在此分享也希望大家不吝賜教