我正在尝试使用 AJAX 通过 API 执行 POST 请求。由于某种原因,我遇到了此错误:“解析请求参数时发生错误”。
据我了解,这个错误是由于我将url属性传递到POST请求时进行json解析而发生的。
我在互联网上阅读了各种 stackoverflow 帖子,似乎使用以下内容应该可行:
data: { todo: { user_id: userId, body: todoBody } },
datatype : 'json',
我也尝试过使用这个,但它不起作用
data: { "todo": { "user_id": userId, "body": todoBody } },
datatype : 'json',
我希望有人能帮助引导我走向正确的方向:)
完整代码如下:
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>
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) {
}
});
});
});
};
最佳答案
尝试使用这个:
$.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);
},
关于jquery - 通过 API 的 AJAX Post 请求 - 解析请求参数时发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27290501/