如何使用哈希提取URL参数


How can I extract URL parameters with hash?

可能重复:
为什么URL的哈希部分不在服务器端?

我有一个URLhttp://www.example.com/edit-your-profile/#file%5B0%5D%5Bstatus%5D=Complete&文件%5B0%5D%5RemoteFileURL%5D=http%3A%2F%2Fi.imgur.com%2Fe0XJI.jpg;文件%5B0%5D%5BfileSource%5D=上一个%20上传&文件%5B0%5D%5PicID%5D=p43

我需要在页面上回显或显示"remoteFileURL"参数作为输入字段的值,似乎我无法使用PHP(据我所知)。我不太了解js,如有任何帮助,不胜感激!

简化-不美观。。。只是为了展示一种可能性并为你指明正确的方向。返回http://i.imgur.com/e0XJI.jpg

<?php
$url = 'http://www.example.com/edit-your-profile/#file%5B0%5D%5Bstatus%5D=Complete&file%5B0%5D%5BremoteFileURL%5D=http%3A%2F%2Fi.imgur.com%2Fe0XJI.jpg&file%5B0%5D%5BfileSource%5D=Previous%20Uploads&file%5B0%5D%5BpicID%5D=p43';
$urlDecoded = urldecode($url);
$urlParts = parse_url($urlDecoded);
$matches = array();
$regexRemoteUrl = preg_match('/remoteFileUrl']=([^&]+)/i', $urlParts['fragment'], $matches);
// remoteFileURL
echo($matches[1]);
?>

您可以使用regex搜索任何与"remoteFileUrl"匹配并后跟一些字符的内容。。。然后在每次安培数时分开绳子。。。然后简单地将该文本字符串回显到您的输入字段中。

如果你想在Javascript中使用它,这里有一个简单的正则表达式:

decodeURI(window.location.hash).match(/remoteFileURL]=([^&]+)/)[1]

它为我返回"http%3A%2F%2Fi.imgur.com%2Fe0XJI.jpg"

所以我们使用unescape:

unescape(decodeURI(window.location.hash).match(/remoteFileURL]=([^&]+)/)[1])

获取"http://i.imgur.com/e0XJI.jpg"

var decodedUri = decodeURIComponent('http%3A%2F%2Fdtzhqpwfdzscm.cloudfront.net%2F4ca06373624db.jpg');

您可以使用此函数从url中提取u所需的参数。

function getURLParameter(name,url) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(decodedUri)||[,null])[1]
    );
}

按以下调用函数

 var fileUrl = getURLParameter("remoteFileURL",decodedUri);

:)

下面是一个可以在JavaScript或php:中使用的正则表达式

(?:file%5B0%5D%5BremoteFileURL%5D|remoteFileURL)=(.+?)&

由于您的示例URL具有一种非常奇怪的参数命名形式,因此我包含了该形式和常用方式。它匹配file[0][remoteFile]remoteFile,并捕获该参数的值。

在JavaScript中,如果有一个包含id为URL的URL的字段,您可以这样做。

var url = document.getElementById('URL').value;
var myRegexp = /(?:file%5B0%5D%5BremoteFileURL%5D|remoteFileURL)=(.+?)'&/;
var match = myRegexp.exec(url);
alert(match[1]);
  • 在Rubular测试
  • 试试jsFiddle