简体   繁体   English

Ajax - JSON不会仅在PATCH中发送

[英]Ajax - JSON doesnt get sent in PATCH only

I am trying to send json data from the client to my server using this: 我正在尝试使用以下方法将json数据从客户端发送到我的服务器:

$.ajax({
    url : 'http://127.0.0.1:8001/api/v1/pulse/7/',
    data : data,
    type : 'PATCH',
    contentType : 'application/json'
)};

I get a No JSON object could be decoded . 我得到一个No JSON object could be decoded However when i use PUT the json object gets sent. 但是,当我使用PUT ,json对象被发送。

It only doesnt work for PATCH 它只适用于PATCH

The backend is Django and the app im using is tastypie 后端是Django,使用的应用程序是tastypie

First, check that you use latest version of jQuery library: 首先,检查您是否使用最新版本的jQuery库:

  • Older versions directly restrict unknown methods (PATCH is new one). 旧版本直接限制未知方法(PATCH是新方法)。
  • I've tested on jQuery 1.7 - PATCH method working without problems. 我已经测试了jQuery 1.7 - PATCH方法没有问题。

Second, not all browsers supports PATCH method using XMLHttpRequest: 其次,并非所有浏览器都支持使用XMLHttpRequest的PATCH方法:

  • Like, IE 7,8 (9+ works okay) have XMLHttpRequest, but it throws an error on PATCH: 就像,IE 7,8(9+工作正常)有XMLHttpRequest,但它在PATCH上抛出一个错误:

     new XMLHttpRequest().open('PATCH', '/'); //Illegal argument 
  • To fix this, you may force jQuery to use the old proprietary ActiveXObject xhr, like so: 要解决此问题,您可以强制jQuery使用旧的专有ActiveXObject xhr,如下所示:

     $.ajax({ url : 'http://127.0.0.1:8001/api/v1/pulse/7/', data : data, type : 'PATCH', contentType : 'application/json', xhr: function() { return window.XMLHttpRequest == null || new window.XMLHttpRequest().addEventListener == null ? new window.ActiveXObject("Microsoft.XMLHTTP") : $.ajaxSettings.xhr(); } }); 

A bit late, but this worked for me when I got this error: 有点晚了,但是当我收到这个错误时,这对我有用:

$.ajax({
  url : 'http://127.0.0.1:8001/api/v1/pulse/7/',
  data : JSON.stringify(data),
  type : 'PATCH',
  contentType : 'application/json',
  processData: false,
  dataType: 'json'
});

Serializing the object yourself instead of letting jQuery do it seems to help. 自己序列化对象而不是让jQuery这样做似乎有所帮助。 This works for me on the latest version of Chrome, but still doesn't fix the ie problems mentioned in other responses. 这适用于我最新版本的Chrome,但仍然无法修复其他响应中提到的问题。

var request = new XMLHttpRequest();
request.open('PATCH', 'http://127.0.0.1:8001/api/v1/pulse/6/', false);
request.setRequestHeader("Content-type","application/json");
request.send('{"isActive": 1}');

Using a an XMLHttpRequest solves it! 使用XMLHttpRequest解决了它!

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

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