zoukankan      html  css  js  c++  java
  • (24)ajax上传json格式的数据

    urs.py


    from django.conf.urls import url
    from django.contrib import admin
    from app01 import views
    urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$',views.index),
    url(r'^upload_file/$',views.upload_file)
    ]

    views.py

    from django.shortcuts import render,HttpResponse
    from app01 import models
    from django.http import JsonResponse
    # Create your views here.

    def index(request):
    return render(request,'index.html')


    def upload_file(request):
    '''文件上传'''
    import json
    dic = {'status':100,'msg':None}
    if request.method == 'POST':
    # post形式上传json格式数据,POST中没有值,在body中取出
    upload_dic = json.loads(request.body)
    name = upload_dic['name']
    pwd = upload_dic['pwd']
    user = models.User.objects.filter(name=name,pwd=pwd).first()
    if user:
    dic['msg'] = '登陆成功'
    else:
    dic['status'] = 101
    dic['msg'] = '账号或密码错误'
    # 这里注意返回一定是Json格式返回
    return JsonResponse(dic)

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="/static/jquery.js"></script>
    <title>ajax</title>
    </head>
    <body>
    <h1>Ajan实现json格式的数据传输</h1>
    <p>用户名:<input type="text" name="'name" id="name"></p>
    <p>密码:<input type="password" name="pwd" id="pwd"></p>
    <button id="btn2">点击登录</button>
    <span id="errors"></span>

    </body>
    <script>
    $("#btn2").click(function () {
    var upload_data = {name:$('#name').val(),pwd:$('#pwd').val()}
    {#js语法把字典格式转成json格式字符串#}
    var upload_json = JSON.stringify(upload_data)
    {#js语法把json字符串转成原生的格式#}
    {#var json_parse = JSON.parse(upload_data)#}
    $.ajax({
    url: '/upload_file/',
    type: 'post',
    contentType: 'application/json', //指定格式为json格式
    data: upload_json,
    success: function (data) {
    console.log(data)
    if (data.status==100){
    location.href = 'http://www.baidu.com'
    }else{
    $('#errors').text(data.msg)
    }
    }
    })
    })
    </script>
    </html>
  • 相关阅读:
    服务器raid故障恢复数据过程
    HP FC MSA2000服务器磁盘掉线数据恢复案例
    服务器存储共享文件夹丢失数据恢复检测报告
    Hp DL380服务器瘫痪如何恢复服务器数据【多图】
    服务器存储瘫痪导致大量虚拟机丢失恢复数据过程
    华为5800服务器raid阵列数据恢复成功案例
    IBM X3850服务器虚误删除虚拟机如何恢复数据
    orcale数据库基本操作
    2、HTML基础知识
    1、web前端的发展
  • 原文地址:https://www.cnblogs.com/shizhengquan/p/10552383.html
Copyright © 2011-2022 走看看