2012-04-15 38 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