我正在用 Django 和 JavaScript 制作表單
單擊按鈕后,我需要顯示一個表單,該按鈕將被回答,并將回傳(以 JSON 格式)帶有答案的串列。
我的代碼 index.js
document.querySelector("#create-blank-form").addEventListener("click", () => {
const csrf = Cookies.get('csrftoken');
fetch('/form/create', {
method: "POST",
headers: {'X-CSRFToken': csrf},
body: JSON.stringify({
title: "Untitled Form"
})
})
.then(response => response.json())
.then(result => {
window.location = `/form/${result.code}/edit`
})
})
錯誤,錯誤指向 .then(result...)
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Promise.then (async)
(anonymous)
我的觀點.py
def create_form(request):
print('hi')
# Creator must be authenticated
# Create a blank form API
if request.method == "POST":
print('hi')
data = json.loads(request.body)
title = data["title"]
code = ''.join(random.choice(string.ascii_letters string.digits) for x in range(30))
choices = Choices(choice = "Option 1")
choices.save()
question = Questions(question_type = "multiple choice", question= "Untitled Question", required= False)
question.save()
question.choices.add(choices)
question.save()
form = Form(code = code, title = title, creator=request.user)
form.save()
form.questions.add(question)
form.save()
return JsonResponse({"message": "Sucess", "code": code})
我的.html
<div class="form-template-box">
<img src = "{% static 'Icon/blank-form.png' %}" alt = "Blank form" title = "Blank form" id="create-blank-form">
<span class="form-template-label">Blank Form</span>
</div>
我的網址.py
path('form/create', views.create_form, name="create_form"),
編輯
我的問題是 urls.py 中的 url,我的代碼的另一部分由于某種原因以一種不好的方式影響。感謝您的評論,他們幫助我找到了錯誤
uj5u.com熱心網友回復:
我認為您的函式存在一些回傳錯誤而不是 JSON 回應的問題。所以 in.then(response => response.json())會引發錯誤。您可以嘗試下面的示例來檢查錯誤。
if request.method == "POST":
try:
print('hi')
data = json.loads(request.body)
title = data["title"]
code = ''.join(random.choice(string.ascii_letters string.digits) for x in range(30))
choices = Choices(choice = "Option 1")
choices.save()
question = Questions(question_type = "multiple choice", question= "Untitled Question", required= False)
question.save()
question.choices.add(choices)
question.save()
form = Form(code = code, title = title, creator=request.user)
form.save()
form.questions.add(question)
form.save()
return JsonResponse({"message": "Sucess", "code": code})
except Exception as err:
return JsonResponse({"message": "Failed", "error": err})
和
.then(result => {
console.log("DEBUG result: ", result);
window.location = `/form/${result.code}/edit`
})
uj5u.com熱心網友回復:
該錯誤SyntaxError: Unexpected token < in JSON at position 0表明回應的第一個字符是“<”,并表明給出的回應是 XML 格式而不是 JSON。
所以response.json()不會起作用,因為response它不是有效的 JSON。如果是,第一個字符將是“{”或“[”。
我建議您使用 console.log() 檢查其格式的回應,然后提取您要使用的“代碼”元素:
const parser = new DOMParser();
const doc = parser.parseFromString(response, 'text/xml');
const codeYouWant = doc.getElementsByTagName("code")[0].innerHTML;
uj5u.com熱心網友回復:
我的問題是 urls.py 中的 url,我的代碼的另一部分由于某種原因以一種不好的方式影響。感謝您的評論,他們幫助我找到了錯誤
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/492850.html
標籤:javascript django 阿贾克斯 django-forms
上一篇:會話過期后重定向到登錄頁面
