简体   繁体   English

XML解析错误:找不到根元素(django + AJAX)

[英]XML Parsing Error: no root element found (django+AJAX)

I'm trying to send a POST request using formdata. 我正在尝试使用formdata发送POST请求。 But this error comes out in FF and status code 400. XML Parsing Error: no root element found Location: http://127.0.0.1:8000/ajax/set_user_profile/ . 但是此错误在FF和状态代码400中出现。XML分析错误:找不到根元素位置: http : //127.0.0.1 : 8000/ajax/set_user_profile/ On the server logs, the request to the function does not even reach. 在服务器日志上,对该功能的请求甚至都没有达到。 I have another POST request that works without problems, but this one does not work. 我还有另一个POST请求,可以正常工作,但是这个请求不起作用。 Also i'm checked html with w3c validator. 我也用w3c验证器检查了html。 all its ok. 一切正常。

JS JS

function set_user_profile(e){
  e.preventDefault();
  let csrf_token = document.getElementById("profile-menu-csrf").value;
  let form = document.getElementById("profile-form");
  let formData = new FormData(form);
  let xhr = new XMLHttpRequest();
  xhr.open('POST', '/ajax/set_user_profile/', true);
  xhr.setRequestHeader('Content-Type', 'multipart/form-data')
  xhr.setRequestHeader('X-CSRFToken', csrf_token);
  xhr.onreadystatechange = function(){
      if(xhr.readyState === 4 ){
          if (xhr.status === 200){
              console.log('ok');
          }
          else{
              console.error(xhr.status);    
          }
      }
  };
  xhr.send(formData);
  }

HTML form like this 这样的HTML表单

<form id="profile-form">
  <input name="csrfmiddlewaretoken" value="${csrf_token}" type="hidden" id="profile-menu-csrf">
  <input type="text"/>
  <textarea></textarea>
  <input type="text"/>
  <input type="text"/>
  <input type="text"/>
  <input type="submit"/>
</form>

URL conf URL配置

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/$', generic.RedirectView.as_view(url='/accounts/login', permanent=False), name='login'),
url(r'^register/$', views.registration, name='registration'),
url(r'^webchat/$', views.home, name="home"),
url(r'^ajax/add_chat/$', ajax.add_chat, name='add_chat'),
url(r'^ajax/update_chats/$', ajax.update_chats, name='update_chats'),
url(r'^ajax/load_messages/$', ajax.load_messages, name='load_messages'),
url(r'^ajax/who_online/$', ajax.who_online, name="who_online"),
url(r'^ajax/get_user_profile/$', ajax.get_user_profile, name="get_user_profile"),
url(r'^ajax/set_user_profile/$', ajax.set_user_profile, name='set_user_profile'),
] 

Django view just for testing Django视图仅用于测试

def set_user_profile(request):
    data = {}
    data['ok'] = 'ok'
    return JsonResponse(data)

Damn, it was so easy. 该死,这很容易。 Just need to remove the header content-type. 只需删除标题的内容类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM