gpt4 book ai didi

javascript - 发布包含 javascript 变量或函数的隐藏字段?

转载 作者:行者123 更新时间:2023-11-28 08:04:45 26 4
gpt4 key购买 nike

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

我有一个页面,其中包含相当长的 php 代码块(主要是 MySQL 查询),这些代码生成的变量最终作为字符串传递到 JavaScript 中。然后,该数据用于创建一些交互式表单元素。最终结果是一个文本区域字段,其中包含一个 JS 字符串,我想将其带入新页面。我还将 POSTing 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'];

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

最佳答案

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

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

关于javascript - 发布包含 javascript 变量或函数的隐藏字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24928040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com