problem description
I wanted to do a form verification to familiarize myself with the functions of ajax, but after typing the same code in the tutorial, my django could not receive the data sent by the page ajax. All I received was debugged by none, step by step, and I could not find the problem. Later, I set up another app to write a form verification, but django could receive the data from ajax and return data,. I don"t know what went wrong with the original code, and csrf commented it out. Still can"t get ajax data.
the environmental background of the problems and what methods you have tried
has tried to add {% csrf_token%}, but it is useless to comment out the csrf intercept in setting.py.
in addition, compare your own code with the tutorial, it"s the same, but the tutorial uses django1.8, "s own 2.0, I don"t know if it"s a version problem? You can"t replace your own code with the source code in the tutorial
related codes
/ / Please paste the code text below (do not replace the code with pictures)
views file:
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"] = ""
return HttpResponse(json.dumps(ret))
urls.py file:
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 Code: (< body > part)
< form id= "add_form" action= "/ host/" method= "POST" >
{% csrf_token %}
:<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">
{% 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(){
$("-sharpa1").click(function(){
$.ajax({
url:"/ajax/",
type:"PSOT",
data:$("-sharpadd_form").serialize(),
success:function(data){
var obj = JSON.parse(data);
if(obj.status){
location.reload()
}else{
$("-sharperror_msg").text(obj.error)
}
}
})
})
})
</script>
what result do you expect? What is the error message actually seen?
need the whole django file test, hope to leave the mailbox, please do me a favor!