开发者

jQuery ajax, intercept script before it's eval'd

Any way I can intercept and modify javascript that gets loaded through ajax?

I need to be able to parse out the script query string into variables and prepend them before it gets evaluated.

Some code i did for jQuery 1.4, but this no longer works for 1.5 and wasn't particularity good.

var oHttpData = jQuery.ht开发者_高级运维tpData, oGlobalEval = jQuery.globalEval, evalUrl = null;
jQuery.extend({
httpData: function(xhr, type, s) {
    if (type === "script")
        evalUrl = s.url;
    console.log(type);
    console.log(s);
    var data = oHttpData.apply(this, [xhr, type, s]);
    evalUrl = null
    return data;
},
globalEval: function(data) {
    if(evalUrl != null && evalUrl.indexOf('?') !== -1) {
        var matches = evalUrl.match(/.*?\?|([\w]*)([\w\+%\.]*)[^&$]/ig), str = '(function() { var ';
        for (var i = 1; i < matches.length; ++i)
            str += matches[i] + '\'' +
                (matches[i + 1] && !(/=/g).test(matches[i + 1]) ? decodeURIComponent(matches[(i++) + 1]) : '') + '\'' +
                (i != matches.length - 1 ? ',' : ';');
        data = str + data + '})();';
    }
    oGlobalEval.apply(this, [data]);
}
});

This would catch the script just before eval and wrap it in a closure with the querystring as variables.


After a little more digging in jQuery I found the method needed.

$.ajaxSetup({
    dataFilter: function(response, type) {
        return response;
    }
});

Allows you to modify the response while still being in the scope of the ajax call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜