Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 解析JSON错误(从PhoneGap到Ruby)_Ruby On Rails_Json_Cordova - Fatal编程技术网

Ruby on rails 解析JSON错误(从PhoneGap到Ruby)

Ruby on rails 解析JSON错误(从PhoneGap到Ruby),ruby-on-rails,json,cordova,Ruby On Rails,Json,Cordova,我正试图将一个JSON字符串从PhoneGap发送到我的Ruby应用程序。在PhoneGap中,以下代码正在发送JSON字符串: var location = { lat: position.coords.latitude, lng: position.coords.longitude } $.ajax({ type: "post"

我正试图将一个JSON字符串从PhoneGap发送到我的Ruby应用程序。在PhoneGap中,以下代码正在发送JSON字符串:

            var location = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            }

            $.ajax({
              type: "post",
              dataType: 'json',
              data: location,
              url: 'http://localhost:3000/location/new'
            });
在我的Ruby应用程序中,我有一个控制器试图处理响应:

def addlocation

    require 'json'
    json_string = params[:data]

    parsed_json = JSON.parse(json_string.to_json)

    if parsed_json["app"] == "Inrix PhoneGap"
        new_obj = Location.new
        new_obj.lat = parsed_json["lat"].to_f
        new_obj.lng = parsed_json["lng"].to_f
        new_obj.save
    end

end
我知道我正在从PhoneGap获取数据,因为参数显示在服务器日志中。我尝试将响应转换为字符串,然后转换为json,因为它似乎不是正确的json格式。我还尝试传递JSON.parse函数response.body和params[:data]。以下是我在服务器日志中收到的错误:

Started POST "/location/new" for 127.0.0.1 at 2013-07-23 01:14:37 -0700
Processing by LocationsController#addlocation as HTML
  Parameters: {"lat"=>"37.785834", "lng"=>"-122.406417"}
Completed 500 Internal Server Error in 0ms

JSON::ParserError (757: unexpected token at 'null'):
  app/controllers/locations_controller.rb:12:in `addlocation'


  Rendered /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
  Rendered /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.9ms)
  Rendered /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (7.5ms)

提前谢谢。如果你需要更多信息,请告诉我。干杯

$中的
数据
。ajax
不是POST参数的名称。您需要提供
数据:{data:location}
,以获得名为
数据的参数(这将转换为POST
数据={“lat”=>“37.785834”,“lng”=>“-122.406417”}

但是,我建议您将其命名为
location
:p

$.ajax({
  type: "post",
  dataType: 'json',
  data: { location: location },
  url: 'http://localhost:3000/location/new'
});


让你明白六个月后你写了什么:D

Doh!我想这意味着该睡觉了。事实证明,我甚至不需要运行JSON.parse函数。我可以这样做:
params[:location][:lat]
谢谢你的帮助!
location_json = params[:location]