2016-03-14 79 views
0

我想在一個網站(在那裏我已經註冊)來發布表單數據,以下是我的代碼:AJAX調用後導致422錯誤

$.ajax({ 
     url:'https://api.contentstack.io/v2/content_types/the_lazy_goose/entries/', 
     type: "POST", 
     contentType: "application/json", 
     data: JSON.stringify({ 
       title: "John", 
       url: "2pm", 
       multi_line: "Random Text using Post call" 
      }), 
     headers:{ 
        access_token: 'xxxxxxxxxxx', 
        api_key: 'xxxxxxxxx' 
       }, 

     success: function() { 
      alert("success"); 
     }, 
     error: function() { 
       alert("ERROR"); 
      }, 
    }); 

這導致422(無法處理的實體) ,不知道哪裏出錯。 *我已經通過了http://www.restpatterns.org/HTTP_Status_Codes/422_-_Unprocessable_Entity並理解「request_entity」 &「的要求語法」都很好

該網站https://contentstackdocs.built.io/rest/api/content-management-api/似乎支持JSON數據

+0

您確定'https:// exampleurl.com/goose/entries /'是允許POST動詞的有效URL嗎?試試這個:http://jsonplaceholder.typicode.com/ – urbz

+0

對不起,我提到的鏈接只是一個隨機文本。我正在發佈的網站允許POST,GET – iyerrama25

+0

好的,你確定那麼你提到的API允許'json'作爲contentType呢?也許不要指定或只是爲了實驗目的,'application/xml'說的是什麼,statuscode ..? – urbz

回答

0

422軌時使用的參數驗證失敗。您可能會缺少一些必需的參數。

此外,我不認爲JSON.stringify在數據是必要的。

0

因此,我瀏覽了他們的contentstack.js文件,並使用它們的Request方法(而不是ajax)POST數據。該架構也是錯誤的。所以這裏是我最後使用的代碼:

function Request(options, callback) { 
     HTTPRequest = XMLHttpRequest; 
     var xhr = new HTTPRequest(), 
      method = options.method || "POST", 
      url = options.url, 
      headers = options.headers; 

     // make a request 
     xhr.open(method, url, true); 

     // set headers 
     xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); 
     for (var header in headers) { 
      xhr.setRequestHeader(header, headers[header]); 
     } 

     // send stringify data 
     if (options.body && method == "POST" || method == "PUT") { 
      if (typeof options.body === 'object') { 
       console.log("sending in data: options.body"); 
       xhr.send(JSON.stringify(options.body)); 
      } else { 
       xhr.send(options.body); 
      } 
     } else { 
      xhr.send(); 
     } 

     // collect response 
     xhr.onreadystatechange = function() { 
      if (xhr.readyState === 4) { 
       var data = xhr.responseText; 
       try { 
        data = JSON.parse(data); 
       } catch (e) { 
        console.error('Could not parse the response received from the server.'); 
       } 

       if (xhr.status >= 200 && xhr.status < 300) { 
        callback(null, data); 
       } else { 
        callback(data, null); 
       } 
      } 
     }; 
    } 

    var options = { 
      url: 'https://api.contentstack.io/v2/content_types/the_lazy_goose/entries/', 
      method:'POST', 
      headers:{ 
         access_token: 'xxxxxxx', //put auth token here 
         api_key: 'xxxxxxx' 
        }, 
      body: { 
         "entry": { 
         "title": "examplexx1", 
         "url": "/example10xxx1", 
         "multi_line": "multiline...!", 
         "_comment": "example comment" 
         } 
       } 
     };