Rails с Fancybox: содержимое ajax не отображается - PullRequest
1 голос
/ 20 февраля 2012

У меня проблема при попытке отобразить всплывающее окно (fancybox) с контентом, отображаемым в контроллере. Fancybox всегда отображает сообщение «Запрашиваемый контент не может быть загружен».

Вот код, который я пытаюсь:

<%= link_to new_item_path(:format => 'js'), :remote => true, :class => 'new_item_popup fancybox.ajax', do %>
    <div class="bubble">
        Add a quick item
    </div>
<% end %>

<script>
    $(document).ready(function(){
        $("#feedback_form").hide();

        $(".new_item_popup").fancybox({
            type        : 'ajax',
            maxWidth    : 800,
            maxHeight   : 600,
            fitToView   : false,
            width       : '70%',
            height      : '70%',
            autoSize    : false,
            closeClick  : false,
            openEffect  : 'none',
            closeEffect : 'none'
        });
    });
</script>

Интересная вещь, которую я заметил в Firebug, заключается в том, что этот код запускает два запроса new.js почти одновременно. Интересно, в этом ли причина этой проблемы?

Использование Rails 3.0, jQuery 1.7.1, последней версии rails.js и Fancybox 2.0.4.

Вот содержимое файла application.html.erb, на всякий случай:

  <%= javascript_include_tag 'jquery-1.7.1.min', 'rails', 'application' %>
  <%= javascript_include_tag 'jquery-ui-1.8.9.custom.min' %>
  <%= javascript_include_tag 'jquery.prettyPhoto' %>
  <%= javascript_include_tag 'jquery.fancybox.pack' %>
  <%= javascript_include_tag 'iphone-style-checkboxes' %>
  <%= javascript_include_tag 'placeholder' %>
  <%= csrf_meta_tag %>

Изменяя параметр типа fancybox на 'iframe', я могу получить всплывающее окно. Но затем во всплывающем окне отображается весь сайт, а не только ответ.

Обновление: оказалось, что этот двойной ajax-запрос вызван этой строкой в ​​application.html.erb:

 <%= javascript_include_tag 'jquery-1.7.1.min', 'rails', 'application' %>

При удалении «рельсов» оттуда также удаляется двойной вызов. Тем не менее, fancybox не отображает содержимое, даже если ответ правильный (проверено через Firebug). Вот содержимое ответа, которое я пытаюсь отобразить через Fancybox:

<div id="create_new_item_window">
    <div class="margin_b"><h2>Create new item</h2></div>
    <div>
    <form accept-charset="UTF-8" action="/items" class="simple_form item" enctype="multipart/form-data" id="new_item" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="authenticity_token" type="hidden" value="RaCmpqXV17piSDljz5VWl0y2INxHTrO5VREAczn+wY4=" /></div>
        <div id="new_item_basic_section">
            <div class="input string required"><label class="string required" for="item_title"><abbr title="required">*</abbr> Title</label><input class="string required" id="item_title" maxlength="35" name="item[title]" required="required" size="30" type="text" /></div>
            <div class="input text optional"><label class="text optional" for="item_description"> Description</label><textarea class="text optional" cols="40" id="item_description" maxlength="450" name="item[description]" rows="20"></textarea></div>
            <div class="input boolean optional"><input name="item[public]" type="hidden" value="0" /><input checked="checked" class="boolean optional right" id="item_public" name="item[public]" type="checkbox" value="1" /><label class="boolean optional" for="item_public"> My friends can see this item</label></div>
            <div class="input boolean optional"><input name="item[giveaway]" type="hidden" value="0" /><input class="boolean optional right" id="item_giveaway" name="item[giveaway]" type="checkbox" value="1" /><label class="boolean optional" for="item_giveaway"> Mark as giveaway</label></div>      
        </div>
        <a href="#" id="show_advanced_section_link" class="amaranth">Add even more details</a>
        <div id="new_item_advanced_section">
            <div class="input text optional"><label class="text optional" for="item_secure_details"> Secure details</label><textarea class="text optional" cols="40" id="item_secure_details" maxlength="450" name="item[secure_details]" rows="20"></textarea><span class="hint">Like serial number and other stuff that will stay private</span></div>
            <div class="input select optional"><label class="select optional" for="item_bookmark_id"> Bookmark</label><select class="select optional" id="item_bookmark_id" name="item[bookmark_id]"><option value="43" selected="selected">updated name</option>
<option value="44">Orange one</option>
<option value="45">Yellow one</option>
<option value="46">Green one</option>
<option value="47">Grey one</option></select><span class="hint">If this list looks empty, try giving some names to your bookmarks</span></div>
            <div class="input string optional"><label class="string optional" for="datepicker3"> Warranty until</label><input class="string optional" id="datepicker3" name="item[warranty_until]" size="30" type="text" /></div>
            <div class="image_attachment">
                <div class="attachment_text">
                    Add some photo <br><small>(JPG, PNG, max 500kb)</small>
                </div>
                <div class="attachment_button">
                    <input id="item_assets_attributes_0_photo" name="item[assets_attributes][0][photo]" type="file" />
                </div>
            </div>
            <div class="image_attachment">
                <div class="attachment_text">
                    Add a receipt <br><small>(JPG, PNG or PDF, max 500kb)</small>
                </div>
                <div class="attachment_button">
                    <input id="item_receipts_attributes_0_photo" name="item[receipts_attributes][0][photo]" type="file" />
                </div>
            </div>
        </div>
        <a href="#" id="hide_advanced_section_link" class="amaranth">Hide details</a>
        <div class="margin_r">
            <input class="button small_button white right" data-disable-with="Saving..." id="item_submit" name="commit" type="submit" value="Create Item" />
        </div>
</form>    </div>
</div>

<script type="text/javascript">  
$(function(){  
    $("#show_advanced_section_link").click(function(event) {  
        event.preventDefault();  
        $("#show_advanced_section_link").hide();
        $("#hide_advanced_section_link").show();
        $("#new_item_advanced_section").slideDown();
    });
    $("#hide_advanced_section_link").click(function(event) {  
        event.preventDefault();  
        $("#hide_advanced_section_link").hide();
        $("#new_item_advanced_section").slideUp();
        $("#show_advanced_section_link").show();
    });
});

$(document).ready(function(){
    $("#new_item_advanced_section").hide();
    $("#hide_advanced_section_link").hide();
});

$(function(){  
    $( "#datepicker3" ).datepicker({
            changeMonth: true,
            changeYear: true
        });
});
</script>

Обновление 2: попытался инициализировать вызов ajax с помощью jquery и передать результат в Fancybox, как это предлагается в комментариях. Не работает, Fancybox вообще не отображается:

$(function(){
    $('.fancybox').click(function(event) {
        event.preventDefault();
        $.ajax('/items/new.js', {
            success: function(result) {
                $.fancybox({ content: result ,type : 'inline', maxWidth : 800, maxHeight : 600, fitToView : false, width : '70%', height : '70%', autoSize : false, closeClick : false, openEffect : 'none', closeEffect : 'none' });
            }
        });
    });
});

Также пробовал вот так (тот же результат):

$(function(){
    $('.fancybox').click(function(event) {
        event.preventDefault();
        $.ajax('/items/new.js', {
            success: function(result) {
                $(result).fancybox();
            }
        });
    });
});

Сам запрос ajax работает нормально, получен правильный ответ.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...