0

我是 Ajax 请求的初学者。

我有一个使用 Prototype 的 Ajax 请求和其他使用 Jquery 的请求。两者都在工作,但前提是我分别给他们打电话。我需要帮助来解决这个冲突。

在我下面展示的代码中,只有“$.fn.bindPostCommentHandler = function()”上的 Ajax 请求才能工作。“new VoteHijacker("link");”上的 Ajax 请求 不管用。

如何使这两个 Ajax 请求一起工作?

这是我网页上的代码。

<html lang="en">
<head>
    <link rel="stylesheet" href="/media/css/base.css" type="text/css" />
    <script src="/media/js/prototype.js"></script>
    <script src="/media/js/getcookie.js"></script>
    <script src="/media/js/prototype.extend.js"></script>
    <script src="/media/js/votehijaker.js"></script>

    <script src="/media/js/jquery-1.8.3.js"></script>
    <script type="text/javascript" charset="utf-8">
        (function( $ ){
        $.fn.bindPostCommentHandler = function() {
            // We get passed a list of forms; iterate and get a unique id for each
            // attach a submit trigger to handle saving and returning
            this.each(function() {
            //$(this).find('input.submit-preview').remove();
            $(this).submit(function() {
                commentform = this;
                commentwrap = $(this).parent();
                $.ajax({
                    type: "POST",
                    data: $(commentform).serialize(),
                    url: "/comments/post/",
                    cache: false,
                    dataType: "html",
                    success: function(html, textStatus) {   
                        // Extract the form from the returned html
                        postedcomment = $(html).find('#newly_posted_comment');
                        //alert(html);
                        $(commentform).replaceWith(postedcomment.html());
                        $(commentwrap).hide();
                        $(commentwrap).slideDown(600);
                        $(commentwrap).find('.comment-form form').bindPostCommentHandler();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $(commentform).replaceWith('Your comment was unable to be posted at this time.  We apologise for the inconvenience.');
                    }
                });
                return false;
            });
            }); //each
        };  
        })( jQuery );

        $(function() {
            $('.comment-form form').bindPostCommentHandler();
        });
    </script>


</head>
<body>
    ...
    ...
    <script type="text/javascript">
    Event.observe(window, "load", function()
    {
        new VoteHijacker("link");
    });
    </script>
    ...
    ...

“VoteHijaker()”上的代码 votehijaker.js 如下:

var VoteHijacker = Class.create();
VoteHijacker.prototype =
{
    initialize: function(prefix)
    {
    this.prefix = prefix || "";
    this.registerEventHandlers();
    },

    registerEventHandlers: function()
    {
    $$("form." + this.prefix + "vote").each(function(form)
    {
        Event.observe(form, "submit", this.doVote.bindAsEventListener(this), false);
    }.bind(this));
    },

    doVote: function(e)
    {
    Event.stop(e);
    var form = Event.element(e);
    var id = /(\d+)$/.exec(form.id)[1];
    var action = /(up|down|clear)vote/.exec(form.action)[1];
    new Ajax.Request(form.action, {
        onComplete: VoteHijacker.processVoteResponse(this.prefix, id, action)
    });
    }
};

VoteHijacker.processVoteResponse = function(prefix, id, action)
{
    return function(transport)
    {
    var response = transport.responseText.evalJSON();
    if (response.success === true)
    {
        var upArrowType = "grey";
        var upFormAction = "up";
        var downArrowType = "grey";
        var downFormAction = "down";

        if (action == "up")
        {
            var upArrowType = "mod";
            var upFormAction = "clear";
        }
        else if (action == "down")
        {
            var downArrowType = "mod";
            var downFormAction = "clear";
        }

        VoteHijacker.updateArrow("up", prefix, id, upArrowType);
        VoteHijacker.updateArrow("down", prefix, id, downArrowType);
        VoteHijacker.updateFormAction("up", prefix, id, upFormAction);
        VoteHijacker.updateFormAction("down", prefix, id, downFormAction);
        VoteHijacker.updateScore(prefix, id, response.score);
    }
    else
    {
        alert("Erro a votar: " + response.error_message);
    }
    };
};

VoteHijacker.updateArrow = function(arrowType, prefix, id, state)
{
    var img = $(prefix + arrowType + "arrow" + id);
    var re = new RegExp("a" + arrowType + "(?:mod|grey)\\.png");
    img.src = img.src.replace(re, "a" + arrowType + state + ".png");
};

VoteHijacker.updateFormAction = function(formType, prefix, id, action)
{
    var form = $(prefix + formType + id);
    form.action = form.action.replace(/(?:up|down|clear)vote/, action + "vote");
};

VoteHijacker.updateScore = function(prefix, id, score)
{
    var scoreElement = $(prefix + "score" + id);
    scoreElement.innerHTML = score.score + " point" + VoteHijacker.pluralize(score.score);
    scoreElement.title = "after " + score.num_votes + " vote" + VoteHijacker.pluralize(score.num_votes);
};

VoteHijacker.pluralize = function(value)
{
    if (value != 1)
    {
    return "s";
    }
    return "";
};

以及“prototype.extend.js”上的代码:

// This is an extend solution to inject in the HEADERS the csrftoken
Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap(
        function (callOriginal, options) {
        var headers = options.requestHeaders || {};
        headers["X-CSRFToken"] = getCookie("csrftoken");
        options.requestHeaders = headers;
        return callOriginal(options);
        }
    );

关于如何使这两个 Ajax 请求一起工作的任何线索?

此致,

4

1 回答 1

1

问题是两个图书馆都想拥有$捷径。jQuery 中有一个使用“无冲突模式”的设置,但这样做需要您将$jQuery 代码中的所有快捷方式替换为其他内容,例如j$.

请参阅:http ://docs.jquery.com/Using_jQuery_with_Other_Libraries

在同一页面中使用 JQuery 和 Prototype

于 2012-12-03T22:10:37.743 回答