html-javascript
var csrftoken = $('[name="csrfmiddlewaretoken"]').val();
$('#Save').click(function () {
var ajaxdata = {
exam: $('#Exam').val()
};
$.ajax({
url: '/save',
type: 'POST',
dataType: 'json',
data: JSON.stringify(ajaxdata),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-CSRFToken": csrftoken
},
credentials: 'include',
success: function () {
alert(ajaxdata);
console.log(ajaxdata);
},
error:function (xhr, ajaxOptions, thrownError){
console.log(ajaxdata);
}
});
}
views.py
import json
from django.http import HttpResponse
def save(request=request):
data = json.loads(request.body)
testexam = data['exam']
testexam = request.POST.get('exam')
testobj = MyObject.objects.filter(name="David").first()
testobj.Exam = testexam
testobj.save()
return HttpResponse(json.dumps({"success": True}), content_type="application/json")
这些是我现在的html和视图。
删除了“烧瓶”部分。
data = json.loads(request.body)
允许我成功接收数据!
还是不太明白为什么“ request.POST”无效。
如果我设法知道原因,我会稍后再回来更新!
感谢您的评论和有用的建议!
答案 0 :(得分:2)
无需使用烧瓶。
这是我接收数据的方式:
data = json.loads(request.body)
一切正常!
感谢所有评论,建议和答案!非常感谢!
答案 1 :(得分:0)
your ajax code is just fine, however you're doing few things wrong. First of all, in your html part.
<h1> This is simple html</h1>
<input type="text" id = "Exam">
<button type="button" id="Save">Save</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var csrftoken = $('[name="csrfmiddlewaretoken"]').val();
$('#Save').click(function () {
var ajaxdata = {
exam: $('#Exam').val()
};
$.ajax({
url: '/save',
type: 'POST',
dataType: 'json',
data: JSON.stringify(ajaxdata),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
"X-CSRFToken": csrftoken
},
credentials: 'include',
success: function () {
alert(ajaxdata)
},
error:function (xhr, ajaxOptions, thrownError){
console.log("this is an error")
}
});
});
</script>
You were initiating the ajaxdata before the click event happened, which may lead to the null value of #Exam
filed.
Now getting back to your Flask part, you can't do request.POST with the data sent through Ajax request. Rather you can access all the data you sent through your js with request.data, below is the code which is working successfully.
from flask import Flask, request,send_from_directory
import json
# set the project root directory as the static folder, you can set others.
app = Flask(__name__)
@app.route('/home')
def root():
#return "this is home"
return send_from_directory("/home/ekbana/Documents/","index.html")
@app.route('/save',methods=['POST'])
def save(request=request):
print(request.data.decode("utf-8")) #We need to decode because it's a byte
#not a string
data = json.loads(request.data.decode("utf-8"))
#data here is {'exam': 'a text'} a dict in this case
testexam = data["exam"]
testobj = MyObject.objects.filter(name="David").first()
testobj.Exam = testexam
testobj.save()
return HttpResponse(json.dumps({"success": True}), content_type="application/json")
This is working fine with me, I replicated a simple example for your requirement. Aslo make sure to use methods=["POST"] if you want your route to recieve the POST request, if you didn't specify it, it may lead to HTTP_405_METHOD_NOT_ALLOWED.