Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

javascript - Ajax - JSON doesnt get sent in PATCH only

I am trying to send json data from the client to my server using this:

$.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. However when i use PUT the json object gets sent.

It only doesnt work for PATCH

The backend is Django and the app im using is tastypie

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, check that you use latest version of jQuery library:

  • Older versions directly restrict unknown methods (PATCH is new one).
  • I've tested on jQuery 1.7 - PATCH method working without problems.

Second, not all browsers supports PATCH method using XMLHttpRequest:

  • Like, IE 7,8 (9+ works okay) have XMLHttpRequest, but it throws an error on PATCH:

    new XMLHttpRequest().open('PATCH', '/'); //Illegal argument
    
  • To fix this, you may force jQuery to use the old proprietary ActiveXObject xhr, like so:

    $.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();
        }
    });          
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...