鍍金池/ 問答/Python  HTML/ django無(wú)法收到ajax的請(qǐng)求數(shù)據(jù)

django無(wú)法收到ajax的請(qǐng)求數(shù)據(jù)

問題描述

本想做一個(gè)表單驗(yàn)證來(lái)熟悉一下ajax的功能,但是跟著教程敲一樣的代碼,自己的django卻沒法接收到頁(yè)面ajax發(fā)送的數(shù)據(jù),接收到的全是none,一步步調(diào)試過(guò),也發(fā)現(xiàn)不了問題,后來(lái)自己另起一個(gè)app寫了一個(gè)表單驗(yàn)證,django卻能收到ajax的數(shù)據(jù)并返回data,不知道原先的代碼出什么問題了,csrf也注釋掉了,還是收不到ajax的數(shù)據(jù)。

問題出現(xiàn)的環(huán)境背景及自己嘗試過(guò)哪些方法

已經(jīng)試過(guò)加上{% csrf_token %} 了,沒用,注釋掉了setting.py里的csrf攔截了。
另外,把自己的代碼和教程做了比對(duì),是一樣的,但是教程用的是django1.8,自己用的是2.0,不知道是不是版本問題?把自己的代碼替換到教程里面的源碼里也不行

相關(guān)代碼

// 請(qǐng)把代碼文本粘貼到下方(請(qǐng)勿用圖片代替代碼)
views文件:
def ajax(request):

ret = {'status':True,'error':None,'data':None}
try:
    h = request.POST.get('hostname')
    i = request.POST.get('IP')
    p = request.POST.get('port')
    c = request.POST.get('agent')
    print(type(h))
    if h and len(h) > 5:
        models.Host.objects.create(hostname = h,ip = i, port = p,b_id = c)
    else:
        ret['status'] = False
        ret['error'] = '太短了'
except Exception as e:
    ret['status'] = False
    ret['error'] = '請(qǐng)求錯(cuò)誤'
return HttpResponse(json.dumps(ret))

urls.py文件:

from django.contrib import admin
from django.urls import path,re_path
from app01 import views

urlpatterns = [

path('admin/', admin.site.urls),
path('host/',views.host),
re_path('business/',views.business),
path('ajax/',views.ajax),]

html代碼:(<body>部分)
<form id="add_form" action="/host/" method="POST">

            {% csrf_token %} 
            主機(jī)名:<input type="text" name="hostname" id="h1"><span id="error_msg"></span><br>
            IP:<input type="text" name="IP" id="i1"><br>
            端口:<input type="text" name="port" id="p1"><br>
            <select name="agent" id="s1">業(yè)務(wù)線
                {% for i in v2 %}
                <option value="{{i.b_id}}">{{i.b__caption}}</option>
                {% endfor %}
            </select>
            <input type="submit" value="提交" >
            <input type="button" value="取消" >
            <a id="a1">ajax提交</a>
       
        </form>

<script src="/static/jquery-3.3.1.js"></script>

<script>
    $(function(){
        $('#a1').click(function(){
            $.ajax({
                url:"/ajax/",
                type:'PSOT',
                data:$('#add_form').serialize(),
                success:function(data){
                var obj = JSON.parse(data);
                if(obj.status){
                    location.reload()
                }else{
                    $('#error_msg').text(obj.error)
                }
                }
            })
        })
    })
</script>

你期待的結(jié)果是什么?實(shí)際看到的錯(cuò)誤信息又是什么?

需要整個(gè)django文件測(cè)試的,希望留下郵箱,請(qǐng)各位大神幫個(gè)忙了!

回答
編輯回答
墨染殤

@csrf_exempt
在你view方法中加個(gè)這個(gè),取消驗(yàn)證

2017年12月1日 01:32
編輯回答
命多硬

POST寫錯(cuò)了??

<script>
    $(function(){
        $('#a1').click(function(){
            $.ajax({
                url:"/ajax/",
                type:'PSOT',     ←這里
                data:$('#add_form').serialize(),
                success:function(data){
                var obj = JSON.parse(data);
                if(obj.status){
                    location.reload()
                }else{
                    $('#error_msg').text(obj.error)
                }
                }
            })
        })
    })
</script>
2017年3月11日 00:40
編輯回答
溫衫

應(yīng)該換成下面這樣

def ajax(request):
    ret = {'status':True,'error':None,'data':None}
    try:
        h = request.POST.get('hostname')
        i = request.POST.get('IP')
        p = request.POST.get('port')
        c = request.POST.get('agent')
        print(type(h))
        if h and len(h) > 5:
            models.Host.objects.create(hostname = h,ip = i, port = p,b_id = c)
        else:
            ret['status'] = False
            ret['error'] = '太短了'
    except Exception as e:
        ret['status'] = False
        ret['error'] = '請(qǐng)求錯(cuò)誤'
    data = json.dumps(ret)
    return HttpResponse(data, content_type='application/json')
2018年3月22日 12:45
編輯回答
心沉

首先是ajax里面的data選項(xiàng)必須傳入一個(gè)key/value格式的數(shù)據(jù),serializer()返回的是一個(gè)字符串,這里肯定有問題。
至于csrf我是添加了header

$.ajax({
    ...
    header: { 'X-CSRFToken':{{ csrf_token }} }

js我不是太懂,你可以說(shuō)試一試

2017年9月3日 00:24