我正在尝试将一个 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)
提前致谢。如果您需要更多信息,请与我们联系。干杯!