2012-04-15 35 views
-1

在我的Rails应用程序中,我正在发出一个ajax请求,作为 $ .ajaxSetup({/ get_paypal_button' });在Rails应用程序中给出错误的Ajax请求

 var dataToSend = { fundraiser_id: <%= @fundraiser.id %>, 
     amount: $("#amount").val(), 
     currency: $('#donor_donation_currency').val(), 
     comment: $('#donor_donation_comment').val(), 
     anonymous: $("#donor_donation_anonymous").is(":checked"), 
     donor_email: $('#email').val(), 
     donor_name: $('#name').val(), 
     donor_city: $('#city').val(), 
     donor_country: $('#country').val() }; 

     $.ajax({ 
     type: "POST", 
     dataType:'JSON', 
     async: true, 
     data:dataToSend, 
     success: function(json){ 
      $('#id_amount').val(json.amount); 
      $('#custom_content').val(json.custom); 
     }, 
     error:function (xhr, ajaxOptions, thrownError){ 
      console.dir(xhr); 
      console.dir(thrownError); 
     } 
     }); 

在控制器我处理的数据作为

def get_paypal_button 
    @fundraiser = Fundraiser.where(:id => params[:fundraiser_id]).last 
    if params[:currency] == 'INR' 
     amount_in_sgd = params[:amount].to_f/@fundraiser.sgd_to_inr.to_f 
    elsif params[:currency] == 'USD' 
     amount_in_sgd = params[:amount].to_f*@fundraiser.usd_to_sgd.to_f 
    else 
     amount_in_sgd = params[:amount].to_f 
    end 

    puts '----------finding donor-------------' 
    @donor = Donor.find_or_initialize_by_email(params[:donor_email]) 
    @donor.update_attributes(:name => params[:donor_name], :city => params[:donor_city], :country => params[:donor_country]) 
    custom = @donor.id.to_s + "::" + params[:anonymous].to_s + "::" + params[:comment].to_s 

    @hash = {:amount => amount_in_sgd, :custom => custom}.to_json 
    respond_with(@hash) do |format| 
    format.json { render :json => @hash } 
    end 

当我使用调试器,并得到@hash它给出的值(这是正确的)

"{\"amount\":15.0,\"custom\":\"2::false::\"}" 

但ajax请求正在执行我编写的代码以防出错,并且它获得空响应。

我已经尝试了一切,完全无能为力,因为类似的代码在几天前工作。

+0

我看到你在你的散列上使用'.to_json' - 你不需要调用它。 – MikDiet 2012-04-15 16:56:51

+0

我也试过,但仍然得到空的回应:( – rtcoms 2012-04-15 17:00:32

+0

它会帮助在数据类型中使用小写json? – DGM 2012-04-15 17:14:50

回答

0

也许format未设置为你希望:

检查Accepts header来自浏览器的作为Ajax调用的一部分。你可以在Firebug的网络标签中看到它。

或转储format到日志并检查它。

+0

的影响,这也是适当的。 URL:http:// localhost:3000/get_paypal_button 请求头文查看源代码 接受:application/json,text/javascript,*/*; q = 0.01 内容类型:application/x-www-form-urlencoded 原产地: http:// localhost:3000 Referer:http:// localhost:3000/fundraisers/1 User-Agent:Mozilla/5.0(X11; Linux i686)AppleWebKit/535.19(KHTML,如Gecko)Chrome/18.0.1025.142 Safari /535.19 X-Requested-With:XMLHttpRe追求 表格数据视图URL编码 fundraiser_id:1 量:13 货币:SGD 评论: 匿名:假 donor_email:[email protected] – rtcoms 2012-04-15 18:28:56

+0

除此之外:: {0 readyState的,responseText的 “”,状态0 ,statusText,“错误”}} – rtcoms 2012-04-15 18:30:54