JSONP

上节回顾

 

 s4day79

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>

</head>
<body>
<input type="button" value="获取用户列表">
<ul id="user_list">

</ul>

    <script src="/static/jquery-3.2.1.js"></script>
    <script>
        function getUsers() {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4){
                    var content = xhr.responseText;
                    console.log(content);
                }
            };
            xhr.open('GET','http://www.s4.com/8000/users/');
            xhr.send();
        }
    </script>
</body>
</html>
jsonp.html
from django.shortcuts import render,HttpResponse,redirect

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

def add1(request):
    a1 = int(request.POST.get('i1'))
    a2 = int(request.POST.get('i2'))
    return HttpResponse(a1 + a2)

def add2(request):
    if request.method == "GET":
        # import time
        # time.sleep(10)
        i1 = int(request.GET.get('i1'))
        i2 = int(request.GET.get('i2'))
        print('add2.....')
        return HttpResponse(i1+i2)
    else:
        print(request.POST)#<QueryDict: {}>
        print(request.body)#请求体: b'i1=12&i2=20'
        return HttpResponse('ok')

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

def fake_ajax(request):
    if request.method == "GET":
        return render(request,'fake_ajax.html')
    else:
        print('POST')
        print(request.POST)#<QueryDict: {'user': ['bingabcd']}>拿到提交的数据
        return HttpResponse('返回值')
import os
def upload(request):
    if request.method == "GET":
        return render(request,'upload.html')
    else:
        print(request.POST,request.FILES)
        file_obj = request.FILES.get('fafafa')
        file_path = os.path.join("static",file_obj.name)#找到文件
        with open(file_path,'wb') as f:#打开文件
            for chunk in file_obj.chunks():
                f.write(chunk)#写文件,上传成功
        return HttpResponse(file_path)

def jsonp(request):
    # import requests
    # request.get()
    # request.post()
    return render(request,'jsonp.html')
views.py jsonp.html

settings.py配置: ALLOWED_HOSTS = ['*']

本机配置一下host

s4day80:

from django.shortcuts import render,HttpResponse
from django.core.wsgi import get_wsgi_application
import json

def users(request):
    print('请求来了')
    user_list = [
        'alex','eric','egon'
    ]
    return HttpResponse(json.dumps(user_list))
views.py users函数 获取用户列表

settings.py配置 ALLOWED_HOSTS = ['*']

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

 

posted on 2017-07-09 02:54  bigdata_devops  阅读(194)  评论(0编辑  收藏  举报

导航