修改通过ajaxSend截获一个jQuery Ajax请求() [英] Modifying a jQuery ajax request intercepted via ajaxSend()

查看:184
本文介绍了修改通过ajaxSend截获一个jQuery Ajax请求()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ajaxSend()拦截请求从一个jQuery插件,在我的网页发起,然后过滤使用ajaxOptions URL无关的请求。

I'm using ajaxSend() to intercept requests originating from a jQuery plugin on my page and then filtering irrelevant requests using the ajaxOptions url.

$('some-selector').ajaxSend(function(e, xhr, settings) {
    var ajaxUrl = settings.url;
    if (ajaxUrl.search('targetpage.aspx') == 0) {
         //need to add an additional parameter to my request here
    } 
}

我需要插入一个额外的参数纳入相关的请求。是否有可能修改此时请求?

I need to insert an additional parameter into relevant requests. Is it possible to modify the request at this point?

推荐答案

这是一个老问题,但我来到这里,从谷歌,并认为其他人搜索同样的事情应该有一个有效的解决方案。我曾尝试建议的答案,但它不工作。修改ajaxSend处理程序中的数据不会改变正在发送

This is an old question, but I came here from Google and thought other people searching the same thing should have a working solution. I have tried the suggested answer but it does not work. Modifying the data in ajaxSend handler does not change what is being sent.

我的目标是一样的OP的,插入一个额外的参数到请求。

My objective was the same as OP's, insert an additional parameter into the requests.

所以我设计的这一个哈克的解决方案:覆盖jQuery的AJAX方法。 只需更换injected_pa​​ram和injected_value,以满足您的需求。我已经添加了一些警卫检查参数是否已经present与否,以防万一。

So I devised a hacky solution for it: override jQuery's ajax method. Just replace "injected_param" and "injected_value" to suit your needs. I've added some guards to check whether the parameter is already present or not, just in case.

$(function() {

        var jqAjax = $.ajax;
        $.ajax = function (settings, settingsObj) {

            if (typeof(settings) == "string") {
                settingsObj.url = settings;
                settings = settingsObj;
            }

            if (!settings.data) { 
                settings.data = {};
            }

            if (typeof(settings.data) == "string" && settings.data.indexOf("&injected_param=") < 0) {
                settings.data += "&injected_param=injected_value";
            }

            else if (!settings.data.injected_param) {
                settings.data.injected_param = "injected_value";
            }


            jqAjax (settings);
        };
    });

这篇关于修改通过ajaxSend截获一个jQuery Ajax请求()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆