AJAX通过API发布请求 - 解析请求参数时发生错误

Jay*_*z55 2 api ajax jquery json ruby-on-rails

我正在尝试使用AJAX通过API执行POST请求.出于某种原因,我遇到了这个错误: "解析请求参数时出错".

根据我的理解,当我将url属性传递给POST请求时,由于json解析而发生此错误.

我已经阅读了互联网上的各种stackoverflow帖子,似乎使用以下应该工作:

data: { todo: { user_id: userId, body: todoBody } },
datatype : 'json',
Run Code Online (Sandbox Code Playgroud)

我也试过使用它,它不起作用

data: { "todo": { "user_id": userId, "body": todoBody } },
datatype : 'json',
Run Code Online (Sandbox Code Playgroud)

我希望有人可以帮助指导我正确的方向:)

以下是完整代码:

index.html.erb

<div class='new-todo'>
    <%= form_for todo, remote: true do |f| %>

      <div class="form-group">
        <%= f.label :body, 'Todo Item' %>
        <%= f.text_area :body, rows: 4, class: 'form-control', placeholder: "Enter todo item" %>
      </div>

      <div class="form-group">
        <%= f.submit "Create", class: 'btn btn-success', data: { user_id: current_user.id, user_token: current_user.auth_token} %>
      </div>

    <% end %>
</div>
Run Code Online (Sandbox Code Playgroud)

Api.js

 var superlist = {};

superlist.setupDeleteHandlers = function() {

  $(document).ready(function(){


    $('.new-todo').submit(function(event) {
      var userId = $('.btn-success').attr("data-user-id");
      var userToken = $('.btn-success').attr("data-user-token");
      var todoBody = $('#todo_body').val();
      var data = {"todo": {"user_id": userId, "body":todoBody}};
      console.log("test", userId, userToken, todoBody, data);
      $.ajax({
        type : "POST",
        url : "/api/users/"+userId+"/todos",
        data: { "todo": { "user_id": userId, "body": todoBody } },
        datatype : 'json',
        contentType: "application/json; charset=utf-8",
        beforeSend: function (xhr) {
          xhr.setRequestHeader ("Authorization", userToken);
        },
        success : function() {
          alert('Item successfully created!'); 
        },
        error : function(error) {
        }
      });
    });

  });

};
Run Code Online (Sandbox Code Playgroud)

jGu*_*pta 7

试试这个:

$.ajax({
    type : "POST",
    url : "/api/users/"+userId+"/todos",
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    beforeSend: function (xhr) {
      xhr.setRequestHeader ("Authorization", userToken);
    },
Run Code Online (Sandbox Code Playgroud)