I am have some issues learning how JavaScript sends data around my application. Right now what I can't figure out is how to get some JSON data back to my Sintra POST route that creates a new database entry. I'm not really getting any error messages and my application shows the data on the screen but it never writes to the database.
Here is my latest unsuccessful attempt
With some alerts I've been able to determine that the JSON I'm sending looks like this
{"description":"test","created_at":"2014-09-25T10:31:29-04:00","updated_at":"2014-09-25T10:31:29-04:00"}
JavaScript Code
t.saveTask = function(task) {
var t = ko.toJSON(task);
$.ajax({
type: "POST",
url: "/tasks/new",
dataType: 'json',
contentType: "application/json",
data:JSON.stringify(t)
}).done(function(){
alert (t);
});
Sintra Code
post "/tasks/new", :provides => :json do
begin
params = JSON.parse(request.env["rack.input"].read)
@task = Task.new
@task.complete = false
@task.description = params[:description]
@task.created_at = DateTime.now
@task.updated_at = DateTime.now
@task.save
rescue Exception => e
return e.message
end
end
尝试在rescue
前先@task.save
,我认为它丢失了。
Thanks everyone. I think I found a solution and I'm sure part of the problem was the @task.save. But in my efforts to fix the issue, I think I may have caused more issues. Here is my updated code that seems to work. Not sure why when I used ko.toJSON(task) it did not work, but with ko.toJS(task)
JavaScript Code
t.saveTask = function(task) {
var t = ko.toJS(task);
alert (t);
$.ajax({
type: "POST",
url: "/tasks/new",
data: t
}).done(function(){
alert (t);
});
}
Sinatra Code
post "/tasks/new" do
content_type :json
@task = Task.new
@task.complete = false
@task.description = params[:description]
@task.created_at = DateTime.now
@task.updated_at = DateTime.now
@task.save
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.