【问题标题】:XML Parsing Error: no root element found (django+AJAX)XML 解析错误:找不到根元素 (django+AJAX)
【发布时间】:2018-09-19 05:18:30
【问题描述】:

我正在尝试使用 formdata 发送 POST 请求。但是这个错误出现在 FF 和状态码 400 中。 XML Parsing Error: no root element found 地点: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>

网址配置

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)

【问题讨论】:

    标签: javascript ajax django


    【解决方案1】:

    该死,这太容易了。只需要删除标题内容类型。

    【讨论】:

      猜你喜欢
      • 2017-09-22
      • 1970-01-01
      • 2017-09-08
      • 2018-06-20
      • 2021-08-26
      • 2017-08-03
      • 1970-01-01
      • 2018-06-06
      相关资源
      最近更新 更多