【问题标题】:Post hidden field containing javascript variable or function?发布包含 javascript 变量或函数的隐藏字段?
【发布时间】:2014-07-24 16:20:12
【问题描述】:

我觉得我一定遗漏了一些东西,或者我太无能而无法搜索正确的问题,所以如果这是重复的,请原谅我(并重定向)。我的问题可能比我想象的要困难得多。

我有一个页面,其中包含相当长的 php 代码块(主要是 MySQL 查询),这些代码生成的变量最终作为字符串传递给 JavaScript。然后使用这些数据来创建一些交互式表单元素。最终结果是一个 textarea 字段,其中包含一个我想带入新页面的 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 变量,因此我无法使用 onload 函数做很多事情。我精通php。我是 JavaScript 的新手。我对 JQuery 相当无能,而且我从未使用过 AJAX。我也真的不想使用cookies。

很高兴看到原始和新页面代码的示例。我知道我可以通过

接收新页面信息上的 php
$foo = $_POST['name2'];

除此之外,我迷路了。安全性并不是真正的问题,因为表单捕获的信息绝不是敏感的。帮忙?

【问题讨论】:

    标签: javascript php html


    【解决方案1】:

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

    预定义语法: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.
                }
            });
        }
    

    【讨论】:

    • @KaribouOfDoom 很高兴我能帮上忙 :) 只是出于兴趣,你是选择 AJAX 还是 jQuery 方法?
    • AJAX,只是因为失败函数有用。可能是我用过的第一个 AJAX 方法!我还有很多东西要学,哈哈。
    【解决方案2】:
    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()`
    

    你有没有尝试过这样的事情

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多