JS包含URL作为URL参数

时间:2013-12-29 23:16:44

标签: javascript

我在JS中有这个脚本,它使用URL参数进行图像定位,当图像与下面的脚本位于同一个地方时,它可以正常工作

<iframe src="pan.htm?image=img1.jpg" ></iframe>

但我需要它来从其他位置获取图像,我该怎么做我尝试了下面的方式,但它不能这样工作(网址只是一个例子)

<iframe src="pan.htm?image=http://someaddress.com/img1.jpg" ></iframe>

2 个答案:

答案 0 :(得分:1)

您需要对网址进行编码。您可以通过运行此脚本来执行此操作:

prompt('Here is your completed code:',encodeURIComponent(prompt('Enter the url to encode','')));

您可以在此处试用: http://jsfiddle.net/zenr8/

脚本为您提供的编码URL是您需要输入URL参数的内容。在您的情况下,iframe将如下所示:

<iframe src="pan.htm?image=http%3A%2F%2Fsomeaddress.com%2Fimg1.jpg" ></iframe>

如果您需要在脚本的URL参数中输入内容,则应始终确保它已正确编码。您可以使用encodeURIComponent执行此操作。如果您需要对其进行解码以便在脚本中进一步使用,请再次使用decodeURIComponent。例如:

alert(encodeURIComponent('http://google.com/?hl=en&q=search'));
//alerts http%3A%2F%2Fgoogle.com%2F%3Fhl%3Den%26q%3Dsearch
alert(decodeURIComponent('http%3A%2F%2Fgoogle.com%2F%3Fhl%3Den%26q%3Dsearch'));
//alerts http://google.com/?hl=en&q=search

答案 1 :(得分:1)

您需要对参数进行urlencode。

<iframe src="pan.htm?image=http%3A%2F%2Fsomeaddress.com%2Fimg1.jpg" ></iframe>

这可以使用php完成,例如:

<iframe src="pan.htm?image=<?php echo urlencode("http://someaddress.com/img1.jpg"); ?>" ></iframe>

with javascript itself

var iframe = document.createElement("iframe");
iframe.setAttribute("src","pan.htm?image="+encodeURIComponent("http://someaddress.com/img1.jpg"));
var wrapper = document.getElementById("iframe_wrapper");
wrapper.appendChild(iframe);
相关问题