ajax只识别json,如果我手动创建它

时间:2013-03-17 12:52:19

标签: ruby ajax json handsontable

我正在尝试使用以下代码检查数据是否已保存:

$parent.find('button[name=save]').click(function () {
  $.ajax({
    url: "/help.json",
    data: {"data": handsontable.getData()}, //returns all cells' data
    dataType: 'json',
    type: 'POST',
    success: function (res) {
      if (res.result === 'ok') {
        $console.text('Data saved');
      }
      else {
        $console.text('Save error');
      }
    },
    error: function () {
      $console.text('Save error, not working');
    }
  });
});

我使用rails作为服务器端代码。如果我手动创建/help.json.erb并将以下内容添加到页面

{
  "result": "ok"
}

当我尝试使用ajax代码时,我收到了“数据保存”消息。

但是,如果我尝试使用ruby创建/help.json文件,我会收到“保存错误,无法正常工作”错误。我在我的控制器中创建/help.json文件的ruby代码如下:

class StaticPagesController < ApplicationController
 respond_to :html, :json

  def home
  end

  def help
      the_hash = {"result"=>"ok"}
      respond_with(the_hash) 
  end
end

以上代码使用

生成/help.json文件
{"result": "ok"}

但我没有收到'数据保存'消息

当我手动创建json文件时它可以工作的原因是什么,但是当我尝试使用ruby时却没有?

我的路线档案的相关部分是:

  root to: 'static_pages#home'
  match '/help',    to: 'static_pages#help'

进一步检查时,我收到的错误消息是500(内部服务器错误)

1 个答案:

答案 0 :(得分:0)

我在这里使用答案解决了这个问题:

Rails respond_with acting different in index and create method

我将respond_with语句更改为:

   respond_with({:result => "ok"}, :location => nil)