我正在尝试编写一个书签,它将从 URL 捕获一些参数并将其发送到脚本(帖子中的 URL 只是一个虚拟的 atm)。
问题是,我尝试将 jQuery 包含到页面中,以便稍后可以使用 $.post。尝试运行小书签时,我在控制台中收到以下错误:
Uncaught ReferenceError: $ is not defined
通过查看浏览器中的“元素”选项卡,我可以看到 jQuery 已成功附加。关于如何解决这个问题有什么建议吗?
您可以看到下面的书签:
javascript:
function appendScript() {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
head.appendChild(script);
}
appendScript();
function parseUri (str) {
var o = parseUri.options,
m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
uri = {},
i = 14;
while (i--) uri[o.key[i]] = m[i] || "";
uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if ($1) uri[o.q.name][$1] = $2;
});
return uri;
};
parseUri.options = {
strictMode: false,
key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q: {
name: "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};
couponCode = parseUri(window.location.search).queryKey['couponCode'];
customerId = parseUri(window.location.search).queryKey['customerId'];
function showModal() {
if (couponCode != null) {
alert("Here is your coupon. Make sure to use it at checkout!" + couponCode);
}
}
showModal();
function parakeetCommunicator() {
if (couponCode != null) {
console.log("Sending data to Parakeet...");
$.post( "http://test.com/datascript.go", { customerId: customerId, couponCode: couponCode })
.done(function( data ) {
console.log("Succesfully posted the coupon was viewed to Parakeet server.");
});
}
}
parakeetCommunicator();
最佳答案
脚本是异步加载的,您可以使用脚本的 onload 事件修复它,例如:
var script = document.createElement("script");
script.onload = parakeetCommunicator;
script.src = ...;
并删除对此方法的其他调用。
如果您只需要 jQuery 作为相对的 ajax 包装器,您应该有兴趣构建自己的 jquery 版本以仅支持这些方法,请参阅:http://projects.jga.me/jquery-builder/
关于javascript - 为小书签从外部加载 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20934610/