如何在同一个网页上执行两个ajax请求?

时间:2012-12-03 21:37:05

标签: jquery ajax prototypejs ajax-request

我是Ajax请求的初学者。

我使用Prototype和其他使用Jquery的Ajax请求。这两个都在工作,但只有我单独打电话给他们。我需要帮助来解决这场冲突。

在我显示的代码中,只有“$ .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请求协同工作的任何线索?

最诚挚的问候,

1 个答案:

答案 0 :(得分:1)

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

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

Using JQuery and Prototype in the same page

相关问题