使用 document.write 動態引入新浪 IP 查詢腳本,試圖在緊隨其後的代碼中讀取該腳本定義的全局變量 remote_ip_info.country,結果為 undefined。即使用 document.write("var gj=...") 能在頁面顯示正確值,但後續拼接 URL 時仍取不到。
document.write 執行是異步的,瀏覽器不保證腳本立即加載完畢並執行。document.write 字符串中寫 var gj=... 雖能在頁面輸出正確值,但這屬於腳本執行上下文,外部作用域無法直接訪問。動態創建 <script> 標籤,利用 onload 事件確保腳本加載完成後再執行後續邏輯:
var myLoader = function(url, callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onload = callback;
document.head.appendChild(script);
};
myLoader("https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=222.5.142.25", function() {
var gj = remote_ip_info.country; // 此時變量已可用
var Url = "https://127.0.0.1:82/tj/cs_tjcs.asp";
var kk = "123";
myLoader(Url + "?kp=" + kk + "&gj=" + gj, function() {});
});
document.write 加載外部腳本。script.onload 保證執行順序。