Is there a way to pass javascript variables in url

2020-01-31 07:11发布

Is there a way to make the below script pass the javascript values to the url of the href link?

<script type="text/javascript">
function geoPreview(lat,long) {
var elemA = document.getElementById("lat").value;
var elemB = document.getElementById("long").value;

window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=elemA&lon=elemB&setLatLon=Set";

}
</script>

5条回答
贼婆χ
2楼-- · 2020-01-31 07:35

Try this:

window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=\''+elemA+'\'&lon=\''+elemB+'\'&setLatLon=Set";
查看更多
We Are One
3楼-- · 2020-01-31 07:41

Do you mean include javascript variable values in the query string of the URL?

Yes:

 window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+var1+"&lon="+var2+"&setLatLon="+varEtc;
查看更多
Bombasti
4楼-- · 2020-01-31 07:51

This is rather over-complicated but will make sense to the inexperienced programmer. In a url, you can include a ‘#’ sign, and anything else can go after that while just going to that page. So you can use js:

var pass = prompt("what do you want to pass")
var site = "https://google.com"
var readysite = site + pass
document.location.replace(readysite)

Then in the other page use JavaScript to read the url and take what information is necessary.

NOTE: the js above is not tested.

查看更多
乱世女痞
5楼-- · 2020-01-31 07:53

Summary

With either string concatenation or string interpolation (via template literals).

Here with JavaScript template literal:

function geoPreview() {
    var lat = document.getElementById("lat").value;
    var long = document.getElementById("long").value;

    window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${lat}&lon=${long}&setLatLon=Set`;
}

Both parameters are unused and can be removed.

Remarks

String Concatenation

Join strings with the + operator:

window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=" + elemA + "&lon=" + elemB + "&setLatLon=Set";

String Interpolation

For more concise code, use JavaScript template literals to replace expressions with their string representations. Template literals are enclosed by `` and placeholders surrounded with ${}:

window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${elemA}&lon=${elemB}&setLatLon=Set`;

Template literals are available since ECMAScript 2015 (ES6).

查看更多
淡お忘
6楼-- · 2020-01-31 07:57

Try this:

 window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+elemA+"&lon="+elemB+"&setLatLon=Set";

To put a variable in a string enclose the variable in quotes and addition signs like this:

var myname = "BOB";
var mystring = "Hi there "+myname+"!"; 

Just remember that one rule!

查看更多
登录 后发表回答