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

时间:2018-09-19 05:18:30

标签: javascript ajax django

我正在尝试使用formdata发送POST请求。但是,此错误在FF和状态代码400中出现。XML分析错误:未找到根元素 位置:http://127.0.0.1:8000/ajax/set_user_profile/。 在服务器日志上,对该功能的请求甚至都没有达到。 我还有另一个POST请求,可以正常工作,但是这个请求不起作用。我也用w3c验证器检查了html。一切正常。

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 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

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视图

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

1 个答案:

答案 0 :(得分:0)

该死,这很容易。只需删除标题的内容类型。

相关问题