How to change external script url onclick?
I have been struggling to find a solution for my issue. I'm not that of a experience person with javascript, but I am looking for a way to slighty change the external js url depending on an onclick event on an ahref.
Right now I have this in my head tags:
<script type="text/javascript" src="http://www.domain.com/loader.php?GID=126&go=&sid="></script>
I want the SID parameter to be set to 1 or 2 based on an onclick on an anchor tag. The loader is called with this piece of code, but the SID would have to change right before the loader is being called.
<a href="/#download" onclick="javascript:Load_126(); return false;">
Is there anyone that could tell me if it's possible? And maybe point me towards the right direction?
Regards,
Sedoc94
EDIT 1 : I have been pointed in a direction and figured I could get this done with jQuery.getScript()
But still have no clue how I should utilize it for my case.
EDIT 2 : As the script need to be pulled from an external domain, I will have to go with the $.ajax() function.
Right now I have:
function loadGame(sid){
$.ajax({
url: 'http://www.domain.com/loader.php?GID=126&go=&sid='+sid,
dataType: "script",
crossDomain: true,
success: gLoad_12603()
});
}
With an ahref onclick I'm calling the loadGame function, but the console says: Uncaught ReferenceError: gLoad_12603 is not defined
. It should be working. But I'm guessing that it somehow gives this error because the function only exists in the script code that is returned from the external URL.
Any ideas how I can make it work?
You need to provide a success callback that will be executed when the AJAX request completes. Right now you are actually saying gLoad_12603() with parathesis and executing the function BEFORE the AJAX request is even initiated. You can't just remove the parathesis because jQuery might try to obtain a reference to the gLoad_12603 function before the AJAX request is actually initiated as well. So you have to wrap your call to gLoad_12603() in a function to ensure everything works out:
function loadGame(sid){
$.ajax({
url: 'http://www.domain.com/loader.php?GID=126&go=&sid='+sid,
dataType: "script",
crossDomain: true,
success: function() {
gLoad_12603();
}
});
}
jQuery.getScript()
function loadScript(sid) {
$.getScript("http://www.domain.com/loader.php?GID=126&go=&sid="+sid, function(script, textStatus, jqxhr) {
//code you want to be executed after the script is loaded inside the page
//you can delete this callback if you don't need it
});
}
并以这种方式使用它,更改每个锚点上的sid
以加载不同的脚本:
<a href="/#download" onclick="javascript:loadScript(126); return false;">
<a href="/#download" onclick="javascript:loadScript(127); return false;">
尝试删除“success:gLoad_12603()”中的括号“()”。
链接地址: http://www.djcxy.com/p/71738.html上一篇: 与Websockets实时聊天
下一篇: 如何更改外部脚本url onclick?