(Django)将数据从javascript(ajax)发送到View

时间:2019-04-23 09:19:25

标签: javascript ajax django

我想通过ajax将模板中的数据(调查数据)发送到服务器,并将此数据作为CSV存储在服务器上。 (我不知道jquery。)当前,URL,视图和Ajax中到处都出现错误。帮帮我如果这是正确的,我将无法理解请求和响应的工作方式...

javascript

function sendToServer(data){
        var req = new XMLHttpRequest();
        req.open("POST", "/polls/upload_csv/", true);
        req.send(data);
    }

urls.py

app_name = 'polls'
urlpatterns = [
    path('', views.index, name = 'index'),
    path('survey/', views.survey, name = 'survey'),
    path('finish/', views.finish, name = 'finish'),
    path('upload_csv/', views.upload_csv, name = 'upload_csv'),
]

views.py

@csrf_exempt
def upload_csv(request):
    output_file = open('/media/result/resultList.csv', 'wb')
    writer = csv.writer(output_file)
    if request.method == 'POST' and request.is_ajax():
        writer.writerow(request.body)

    return 0

(我不知道要写什么,所以我将其留空。)

当前错误:

  1. 内部服务器错误:/ polls / upload_csv /

  2. output_file = open('/ media / result / resultList.csv','wb') FileNotFoundError:[错误2]没有这样的文件或目录:'/media/result/resultList.csv'

  3. “ POST / polls / upload_csv / HTTP / 1.1” 500 75545

  4. 代码400,消息错误的请求语法

0 个答案:

没有答案