Ruby JSON.parse会出现意外的令牌错误

时间:2014-10-30 10:11:41

标签: jquery ruby-on-rails ruby json

我正在发送一个像这样的jQuery的POST

   var authorisationType = "payment";

   var paymentData = {
        cardholdername: $("#userCardName").val(),
        cardnumber: $("#userCardNumber").val(),
        expmonth: $("#userExpMonth").val(),
        expyear: $("#userExpYear").val(),
        cvv:$("#userCVV").val(),
        amount: "$15.00"
    }

    var postData = new Object();
    postData.username = username;
    postData.type = authorisationType;
    postData.data = paymentData;

    var authorisationType = "payment";

    console.log("sending username and token to server");
    $.ajax({
       type: 'POST',
       url: url,
       data: JSON.stringify(postData), 
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: successHandler,
       error: errorHandler
    });  

到我的Rails控制器:

def authorisation_request
    puts "preparse" 
    hash = JSON.parse(params[:username])
    puts "hash" 
    puts "username:" + JSON.parse(params[:username]).to_s + " type:" +  JSON.parse(params[:type]).to_s + " data:" + JSON.parse(params[:data]).to_s
end

我在控制台中收到以下错误:

 Parameters: {"username"=>"me@example.com", "type"=>"payment", "data"=>{"cardholdername"=>"me myself", "cardnumber"=>"xxxxxxxxxxxx3456", "expmonth"=>"01", "expyear"=>"2015", "cvv"=>"999", "
amount"=>"$15.00"}, "session"=>{"username"=>"me@example.com", "type"=>"payment", "data"=>{"car
dholdername"=>"me myself", "cardnumber"=>"xxxxxxxxxxxx3456", "expmonth"=>"01", "expyear"=>"2015"
, "cvv"=>"999", "amount"=>"$15.00"}}}

preparse
Completed 500 Internal Server Error in 4ms

JSON::ParserError (757: unexpected token at 'me@example.com'):
  app/controllers/sessions_controller.rb:119:in `authorisation_request'

我做错了什么?

2 个答案:

答案 0 :(得分:4)

params[:username]包含不是有效JSON的字符串(me@example.com)。您无需为此致电JSON.parse

答案 1 :(得分:3)

如果你从jQuery发布这样的数据,它会更干净,更容易:

var postData = new Object();
postData.userdata = { 'username': username, 
                      'type': authorisationType,
                      'data': paymentData };

现在,在控制器中,你可以:

def authorisation_request
  puts params[:userdata]
end

不需要JSON.parse因为参数中的所有值都可以使用params作为键值对。