【发布时间】:2020-04-14 18:08:55
【问题描述】:
这是我的 javascript 函数,用于更新我的数据库。但是,我收到两个错误:
- 不允许的方法:/users/update_contact/"
- SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列的数据意外结束
最后,我的数据库没有更新。
下面是调用函数的按钮:
<button onclick="update_contact()" class="update_contact">Update Contact Info</button>
Django 视图:
class UserContactUpdate(View):
model = Contact
fields = ["github_profile_link", "phone_number", "email_address"]
git = "https://www.github.com/"
def get_object(self):
return get_object_or_404(Contact)
def get_success_url(self):
return reverse("users:view_profile")
def post(self, request, *args, **kwargs):
contact = self.get_object()
contact.github_profile_link = self.git + request.POST['github_username']
contact.mobile_number = request.POST['mobile_number']
contact.email_address = request.POST['email']
contact.save()
print ("contact link is" + contact.github_profile_link,
"mobile number is" + contact.mobile_number,
"email adress is " + contact.email_address)
return HttpResponse("contact saved")
update_contact = UserContactUpdate.as_view()
Django 网址:
path('update_contact/', view=update_contact, name="update_contact"),
function update_contact (){
url = "{% url 'users:update_contact' %}";
git_profile = prompt("enter git profile name")
phone = prompt("enter phone number")
email = prompt("enter email address")
const contact = {
"git_profile" : git_profile,
"phone_number" : phone,
"email" : email
};
var stringify_contact = JSON.stringify(contact);
const options = {
method: 'POST',
body: JSON.parse(stringify_contact),
mode: 'same-origin',
dataType: 'json',
headers : {
'content-Type' : 'application/json',
'X-CSRFToken': csrftoken,
}
}
fetch(url, options)
.then(res => res.json())
.then(res => console.log(res))
}
【问题讨论】:
-
你为什么要对你的 json 进行字符串化,然后才对其进行解析?无论如何,发送字符串化版本并在 python 中解析通常对我有用。
-
我一开始试过了,也没有用。我点击了一个链接,他们建议这样做。
标签: javascript django