我假设您对 HTML 和 HTTP 不是很满意,并且您正在学习,因此没有调查页面的源代码以了解发生了什么。
这完全没问题。
这是该页面源代码的简化版本:
<form id="tryitform" name="tryitform"
action="tryit_view.asp" method="post"
target="view"
onsubmit="validateForm();">
Source Code: <input type="button" value="Submit Code »"
onclick="submitTryit()">
Result: <textarea id="pre_code">
<!-- Your source code goes here -->
</textarea>
<input type="hidden" id="code" name="code" />
<input type="hidden" id="bt" name="bt" />
<iframe id="viewIFRAME" name="view"
src="tryit_view.asp?filename=tryjsref_loc_host">
</iframe>
</form>
<script type="text/javascript">
// This Script is called when you press the "Submit Code" button
function submitTryit()
{
// I'll omit the code, but what it does is this:
// 1. Take the text (your code) in the 'pre_code' textarea
// and substitute '=' with 'w3equalsign'
// and 'script' with 'w3scrw3ipttag'.
// 2. Put the modified text in the 'code' hidden input field
// 3. Change the form's action to "tryit_view.asp?x=" + a random number
// 4. Call validateForm(), which basically
// only checks if the code doesn't exceed 5000 characters
// 5. Submit form
}
window.onload = function(){ submitTryit() }
// Call submitTryit() when the page first loads
// so the view is filled also when you first arrive.
</script>
这里要理解的关键思想是,您编写的代码以action属性设置为“tryit_view.asp?x=”+ 一个随机数的形式进行,并且该target属性设置为“view”。表单上的这个target属性意味着表单提交的结果应该出现在iframe上,该 iframe的属性name设置为“view”。
所以你看,问题是你的代码实际上并没有在你在浏览器上看到的页面上运行。它实际上是通过 POST 发送到服务器的。
然后服务器响应一个不同的页面来填充 iframe 的内容。
iframe 基本上是嵌套在主页内的“矩形迷你浏览器”,它有一个不同的 URL,与主页的 URL 无关,也不会出现在地址栏上。此 URL 是表单操作的 URL。
现在大概服务器响应 POST 所做的只是在恢复上面那些奇怪的文本替换之后,使用您提交的代码创建一个 HTML 页面。
所以你的代码最终会在 iframe 中运行。
因此,当您编写window.locationor时location,您的代码最终将实际访问 iframe 的位置,而不是主页的位置。
您可以像这样访问父页面的位置:
// 'parent', same as 'window.parent', refers to
// the frame which is the parent of the frame where
// this code is being run (the iframe named 'view').
document.write( parent.location.search );
或者像这样:
// "top" is the frame at the top of the frame hierarchy
document.write( top.location.search );
祝你学习顺利!