简体   繁体   English

将值从一个html页面传递到另一个html javascript函数

[英]passing the value one html page to another html javascript function

I need to pass the value one html page to another html javascript function using javascript code. 我需要使用javascript代码将一个html页面的值传递给另一个html javascript函数。 How to pass value. 如何传递价值。 Thanks in advance 提前致谢

view.cshtml:
b.on('click', function () {
    document.location.href =  + '?Id=' + sData; // need to pass the value
});

index.cshtml:
function getId(data) { // i need to get the data here
}

You have two choices: 您有两种选择:

  • Save the data at the client, such as in a cookie. 将数据保存在客户端,例如cookie中。
  • Pass it to the service in a GET or POST request, and get the server side script (for example PHP) to pass the value in. 在GET或POST请求中将其传递给服务,并获取服务器端脚本(例如PHP)以将值传递进来。

Through the server, if using PHP for example: 通过服务器(例如,使用PHP):

view.cshtml:
// assume sData = 5
b.on('click', function () {
    document.location.href =  + 'index.php?Id=' + sData;
});

When you click the function is triggered it requests index.php from the server. 当您单击该函数时,它将从服务器请求index.php。

index.php:
<?php
    ...
    echo "var id = $_POST['Id'];";
    echo "function getId() {";
    // Function code here refering to id variable
    echo "}";
    ...
?>

index.php generates: index.php生成:

index.cshtml:
var id = 5;
function getId() {

}

You could retrieve the GET data via Javascript. 您可以通过Javascript检索GET数据。 I've created an example which uses a PHP style syntax: 我创建了一个使用PHP样式语法的示例:

<script>
var $_GET = {};
(function() {
    var params=top.location.search.split("?").join("").split("&");
    for(var i=0;i<params.length;i++){
        var param=params[i].split("=");
        $_GET[param[0]]=param[1];
    }
})();

alert($_GET['Id']);

</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM