我有這樣幾個「邀請」按鈕的觀點:爲什麼不是這個「ajax:success」事件觸發?
<div class = "fbinvite_form" id = "<%= friend[:identifier] %>" name = "fb">
<div class = "btn btn-small">
Invite
</div>
</div>
當其中一個按鈕被點擊的AJAX調用函數(invite_friend):
$('.fbinvite_form').click(function() {
invite_friend();
});
這裏的invite_friend(一些值是被硬編碼爲我調試):
function invite_friend() {
$.post('/groups/7/invitations',
{
"recipient_email": "[email protected]",
"commit" : "fb",
"fb" : "fb"
},
function(response) {
});
}
下面是從控制器返回的相關線路:
render :json => {
:url => signup_with_token_url(@invitation.token),
:id => @invitation.id
},
:status => :created
我可以確認這個json被正確渲染。在這一點上,我期待ajax:success
事件發生。我在我的頁面頂部有以下代碼:
$('.fbinvite_form').bind("ajax:success", function(evt, data, status, xhr) {
...
});
但它沒有發射。任何線索可能會出錯或如何更好地排除故障(我有點小菜鳥)?
附加的上下文
我想添加多一點點,因爲它可能會有所幫助。我最初建立這個與表單一起工作,它工作得很好。出於一些性能原因,我決定使用AJAX切換到按鈕。這裏的原始形式:
<%= form_for([@group, @invitation], :remote => true, :html => { :'data-type' => 'html', :class => 'fbinvite_form', :id => friend[:identifier]}) do |f| %>
<%= f.hidden_field :recipient_email, :value => "[email protected]" %>
<div class = "fbinvite btn_list_right" id = "<%= friend[:identifier] %>">
<%= f.submit "Invite", :class => "btn btn-medium btn-primary", :name => "fb" %>
</div>
<% end %>
現在已經被所有你看到的控制器片斷上面的代碼替換。
更新1
每文斯的建議,我提出了「AJAX:成功」碼到成功的功能。這裏是原始的「阿賈克斯:成功」功能:
$('.fbinvite_form').bind("ajax:success", function(evt, data, status, xhr){
var fb_id = $(this).attr('id');
var response = eval("(" + xhr.responseText + ")");
var link_url = response.url;
var id = response.id;
var inv_url = <%= raw('"' + group_url(@group) + '/invitations/"') %> + id;
var picture_url = "https://www.example.com.com/assets/cody_130by130.png";
var desc = <%= raw('"' + first_name(current_user) + " is working with Cody on fitness. Join " + genderizer(current_user, "his") + " group to start tracking your workouts. Cody and the other group members will keep you motivated!" + '"') %>;
send_invite(fb_id, link_url, picture_url, desc, inv_url); return false;
});
這就是我已經做了將代碼移入成功函數。問題是,我似乎沒有訪問「xhr」
$.ajax({
type: "POST",
url: "/groups/7/invitations",
data: {recipient_email: "[email protected]", commit : "fb", fb : "fb" },
dataType: "json",
success: function(evt, data, status, xhr) {
var fb_id = $(this).attr('id');
var response = eval("(" + xhr.responseText + ")");
var link_url = response.url;
var id = response.id;
var inv_url = <%= raw('"' + group_url(@group) + '/invitations/"') %> + id;
var picture_url = "https://www.meetcody.com/assets/cody_130by130.png";
var desc = <%= raw('"' + first_name(current_user) + " is working with Cody on fitness. Join " + genderizer(current_user, "his") + " group to start tracking your workouts. Cody and the other group members will keep you motivated!" + '"') %>;
send_invite(fb_id, link_url, picture_url, desc, inv_url); return false;
}
});
嘗試在您的AJAX'$ .post'請求中添加'error'處理程序。如果它觸發,那麼意味着你的迴應有錯誤。然後,您將能夠在'error'處理程序中找到並輸入錯誤類型。也嘗試添加'dataType:'json''到您的'$ .post'函數(這是JSON響應所必需的) – bor1s 2012-07-26 07:27:56