简体   繁体   English

使用ajax将json数据发布到sinatra路由并发送到数据库

[英]Using ajax to post json data to a sinatra route and send to a database

I am have some issues learning how JavaScript sends data around my application. 我在学习JavaScript如何在应用程序周围发送数据时遇到一些问题。 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. 现在,我不知道要如何将一些JSON数据返回到Sintra POST路由,该路由会创建一个新的数据库条目。 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 通过一些警报,我已经能够确定正在发送的JSON看起来像这样

{"description":"test","created_at":"2014-09-25T10:31:29-04:00","updated_at":"2014-09-25T10:31:29-04:00"}

JavaScript Code JavaScript代码

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. 我想我找到了解决方案,并且确定问题的一部分是@ 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) 不知道为什么当我使用ko.toJSON(task)时不起作用,但是使用ko.toJS(task)

JavaScript Code JavaScript代码

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 Sinatra代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM