张贴包含javascript变量或函数的隐藏字段

Post hidden field containing javascript variable or function?

本文关键字:隐藏 字段 函数 javascript 变量 张贴包      更新时间:2023-09-26

我觉得我一定遗漏了什么,或者我太无知了,无法搜索正确的问题,所以如果这是重复的,请原谅我(并重定向(。我的问题可能比我认为的要困难得多。

我有一个页面,里面有一段相当长的php代码(主要是MySQL查询(,这些代码生成的变量最终作为字符串传递到JavaScript中。然后使用这些数据来创建一些交互式表单元素。最终的结果是一个文本区域字段,其中包含一个JS字符串,我想将其携带到一个新页面。我还将把php变量张贴到那个新页面上。

样本代码:

<?php //Get data from MySQL, define variables, etc.?>
<script> //Move php strings into JavaScript Strings; 
         //put JS vars into textareas; etc 
         var foo = document.getElementById('bar').value </script>
<form action="newpage.php" method="post">
<input type="hidden" id="id" name = "name" value="**JAVASCRIPT foo INFO HERE**"/>
<input type = "hidden" id="id2" name = "name2" value = "<?php echo $foo; ?>" />
<input type="submit" name="Submit" value="Submit!" />

以正确的顺序调用JS函数有点困难,因为它们依赖于php变量,而php变量在查询完成之前不会定义,所以我不能用onload函数做太多工作。我精通php。我是JavaScript的新手。我对JQuery相当不在行,而且我从未使用过AJAX。我也真的不想用饼干。

如果能看到一个原始和新页面代码可能是什么样子的示例,那就太好了。我知道我可以通过在新页面上接收php信息

$foo = $_POST['name2'];

除此之外,我迷失了方向。安全性并不是一个真正的问题,因为表单捕获的信息绝不是敏感的。帮助

如果你不需要使用failure函数,你可以跳过AJAX方法(它有点重(,所以我建议你使用jQuery$.post$.get语法。

预定义语法:jQuery.post( url [, data ] [, success ] [, dataType ] )

以下是jQuery的示例:

$.post('../controllerMethod', { field1: $("#id").val(), field2 : $("#id2").val()}, 
    function(returnedData){
         console.log(returnedData);
});

否则,您可以使用AJAX方法:

    function yourJavaScriptFunction() {
        $.ajax({
            url: "../controllerMethod",   //URL to controller method you are calling.
            type: "POST",                 //Specify if this is a POST or GET method.
            dataType: "html",
            data: {                       //Data goes here, make sure the names on the left match the names of the parameters of your method you are calling.
                'field1': $("#id").val(), //Use jQuery to get value of 'name', like this.
                'field2': $("#id2").val() //Use jQuery to get value of 'name2', like this.
            },
            success: function (result) {
                //Do something here when it succeeds, and there was no redirect.
            }
        });
    }
function init()
{
    var str1 = <?php echo varname; ?> //to access the php variable use this code//
    document.getElementById('id').value= str1;
}
<body onload="init()">//make sure you call the function init()`

你试过这样的吗