weixin_33686714 2016-08-27 08:04 采纳率: 0%
浏览 45

Rails-Ajax响应处理

I am sending data by using ajax call to 3rd party api to see if the card supports installment, then I get a response in the payment#new action, I just do not know how to show response on the view.

ajax call;

                $.ajax({
                 type: "GET", 
                 url: "/payments/new", 
                 dataType: "json", 
                 data: {card_digit},
                 success: function(data) {}, 
                 error: function(jqXHR) {}
                }); 

payments#new action

def new
...
...
uri = URI.parse("https://...")
      https = Net::HTTP.new(uri.host,uri.port)
      https.use_ssl = true
      req = Net::HTTP::Post.new(uri.path, @headers)


      req.body = @body.to_json
      res = https.request(req)


      puts "Response #{res.code} #{res.message}: #{res.body}"

end

Then here it returns res.body as json object, I would like to show this on the view I have tried to assign to a variable like @return then use it on the view but no chance, I tried with respond to block but could not manage to do it either.

EDIT

Thank you for the answer!, But now I get error Encoding::UndefinedConversionError ("\xC4" from ASCII-8BIT to UTF-8)

res.body returns;

{"bankId":"13","bankName":"...","cardFamilyId":"..","cardFamilyName":"...","cardThreeDSecureMandatory":"0","merchantThreeDSecureMandatory":"0","result":"1","serviceProvider":"2","supportsInstallment":"1","type":"1"}

I wrote;

render json: { res_body: res.body }

and console.log(data) in the success function

why would it happen?

EDIT

I added

render json: { res_body: JSON.parse(res.body) }
  • 写回答

1条回答 默认 最新

  • derek5. 2016-08-27 08:09
    关注

    If you use Ajax then you have to handle it in your JavaScript code to change your view.

    Use this in your controller to pass the data to your Ajax call (replace the dummy hash):

    render json: { test: "hello" }
    

    In your success function of the ajax the JSON object I just rendered will be accessible in the data parameter of the function. Now I have to manipulate the view using javascript

    EDIT:

    To answer your edit I guess you have some characters which are more complicated to handle in your JSON like chinese, turkish, .... Maybe this might help you Encoding::UndefinedConversionError

    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵