ajax基本操作

基本操作:

1在项目s13day18_django的settings配置中,指定jquery的目录,同时注释掉CSRF

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR,'static'),
)

# 'django.middleware.csrf.CsrfViewMiddleware',

2在app01下面,指定路由关系

urlpatterns = [
    # url(r'^index/(\d+)/', views.index),
    # url(r'^detail/(\d+)/',views.detail),
    # url(r'^template/',views.template),
    url(r'^extend/',views.extend),
    url(r'^assets/',views.assets),
    url(r'^userinfo/',views.userinfo),
    url(r'^ajax_demo/',views.ajax_demo),
]

3在app01下面,定义ajax_demo函数

def ajax_demo(request):
    if request.method == 'POST':
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        print(user,pwd)
        if user == '111' and pwd == '222':
            return HttpResponse('1')
        else:
            return HttpResponse('2')
    return render(request,'ajax_demo.html')

4 在templates中,添加关于ajax_demo的HTML信息

 


    

用户名: "text" id="username" />

密码: "password" id="pwd" />

"button" value="提交" οnclick="SubmitForm();"/>

过程流程:整个执行的过程是,ajax传递参数给了函数ajax_demo,函数获取到用户键入的值,然后通过HttpResponse返回给回调函数success,回调函数再执行相应的操作。

 

二  但是在实际的使用中,我们要这么定义views.py

import json
def ajax_demo(request):
    if request.method == 'POST':
        ret = {'status':False,'message':''}
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        print(user,pwd)
        if user == '111' and pwd == '222':
            ret['status'] = True
            return HttpResponse(json.dumps(ret))
        else:
            ret['message'] = '用户名或密码错误'
            return HttpResponse(json.dumps(ret))
    return render(request,'ajax_demo.html')

  ajax_demo.html


    

用户名: "text" id="username" />

密码: "password" id="pwd" />

"button" value="提交" οnclick="SubmitForm();"/>

 

转载于:https://www.cnblogs.com/systemsystem/p/10918372.html

你可能感兴趣的:(ajax基本操作)