我需要使用 Javascript/jQuery 从 URL 获取一些参数,我发现了这个不错的函数:
function getURLParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
};
所以我开始在我的代码中使用,但我遇到了一些问题,因为我正在寻找的参数是未定义
。首先,这是一个 Symfony2 项目,因此 Profiler
为我提供了以下信息:
Request Attributes
Key Value
_route_params [registro => 1, solicitud => 58]
...
registro 1
solicitud 58
我在这里需要的是registro
和solicitud
。所以我在 Javascript 方面所做的是:
console.log(getURLParameter('registro')); // gets undefined
但令人惊讶的是,我得到了未定义
,我认为原因是registro
不存在于http://project.dev/app_dev的URL中。 php/proceso/1/58/modificar
但它存在于请求中。如何从 JavaScript 中获取 registro
和 solicitud
值?我需要将这些参数发送到 Ajax 调用,有什么建议吗?
最佳答案
尝试使用此功能:
function getParameters(){
var url = window.location.href; //get the current url
var urlSegment = url.substr(url.indexOf('proceso/')); //copy the last part
var params = urlSegment.split('/'); //get an array
return {registro: params[1], solicitud: params[2]}; //return an object with registro and solicitud
}
然后您可以调用该函数并使用这些值:
var params = getParameters();
console.log(params.registro);
console.log(params.solicitud);
关于javascript - 从 Javascript|jQuery 和 Symfony2 项目中的 URL 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28481154/