我正在尝试从HTML中读取发布请求参数。我可以使用以下JavaScript代码读取get请求参数。
$wnd.location.search
但这不适用于发布请求。谁能告诉我如何使用JavaScript读取HTML中的发布请求参数值?
Answers:
POST数据是在服务器端处理的数据。Javascript位于客户端。因此,您无法使用JavaScript读取帖子数据。
使用一小段PHP即可让服务器填充一个JavaScript变量,这是快速简便的:
var my_javascript_variable = <?php echo json_encode($_POST['my_post'] ?? null) ?>;
然后只需以常规方式访问JavaScript变量即可。
请注意,除非您进行检查,否则不保证任何给定的数据或某种数据将被过帐-所有输入字段均为建议,而非保证。
JavaScript是一种客户端脚本语言,这意味着所有代码都在Web用户的计算机上执行。另一方面,POST变量将转到服务器并驻留在该服务器上。浏览器不会将这些变量提供给JavaScript环境,任何开发人员也不应期望它们会神奇地出现在其中。
由于浏览器禁止JavaScript访问POST数据,因此如果没有外部参与者(如PHP)将POST值回显到脚本变量或捕获正在传输的POST值的扩展/附件中,则几乎不可能读取POST变量。GET变量可通过一种解决方法来使用,因为它们位于可以由客户端计算机解析的URL中。
使用sessionStorage!
$(function(){
$('form').submit{
document.sessionStorage["form-data"] = $('this').serialize();
document.location.href = 'another-page.html';
}
});
在another-page.html:
var formData = document.sessionStorage["form-data"];
参考链接-https://developer.mozilla.org/zh-CN/docs/Web/API/Window/sessionStorage
form.on('submit',function(){document.sessionStorage["form-data"] = $('this').serialize();window.location.href = 'another-page.html';})
samesite = None和Secure因此Chrome允许它的使用。
为什么不使用localStorage或任何其他方式设置您想要传递的值?
这样,您可以从任何地方访问它!
通过 任何给定的域/上下文中,我的意思是
cloudianos.com不会到达api.cloudianos.com的JavaScript,因为它们没有共享localStorage。
您可以使用jQuery-PostCapture(@ ssut / jQuery-PostCapture)阅读发布请求参数。
PostCapture插件由一些技巧组成。
单击提交按钮后,onsubmit将调度该事件。
届时,PostCapture将序列化表单数据并保存到html5 localStorage(如果有)或cookie存储中。
如果您使用的是Java / REST API,则解决方法很容易。在JSP页面中,您可以执行以下操作:
<%
String action = request.getParameter("action");
String postData = request.getParameter("dataInput");
%>
<script>
var doAction = "<% out.print(action); %>";
var postData = "<% out.print(postData); %>";
window.alert(doAction + " " + postData);
</script>
<script>
<?php
if($_POST) { // Check to make sure params have been sent via POST
foreach($_POST as $field => $value) { // Go through each POST param and output as JavaScript variable
$val = json_encode($value); // Escape value
$vars .= "var $field = $val;\n";
}
echo "<script>\n$vars</script>\n";
}
?>
</script>
或使用它将它们放入函数可以检索的字典中:
<script>
<?php
if($_POST) {
$vars = array();
foreach($_POST as $field => $value) {
array_push($vars,"$field:".json_encode($value)); // Push to $vars array so we can just implode() it, escape value
}
echo "<script>var post = {".implode(", ",$vars)."}</script>\n"; // Implode array, javascript will interpret as dictionary
}
?>
</script>
然后在JavaScript中:
var myText = post['text'];
// Or use a function instead if you want to do stuff to it first
function Post(variable) {
// do stuff to variable before returning...
var thisVar = post[variable];
return thisVar;
}
这仅是一个示例,不应将其用于任何敏感数据(例如密码等)。将数据安全地发送到后端,这样会达到目的。
但是,如果您只需要一堆不敏感的表单数据而无需/page?blah=value&bleh=value&blahbleh=value输入url,就可以进入下一页,这将使URL更加整洁,并且JavaScript可以立即与POST数据进行交互。
我有一个简单的代码可以做到这一点:
在您的index.php中:
<input id="first_post_data" type="hidden" value="<?= $_POST['first_param']; ?>"/>
在您的main.js中:
let my_first_post_param = $("#first_post_data").val();
因此,当将main.js包含在index.php(<script type="text/javascript" src="./main.js"></script>)中时,您将获得包含输入数据的隐藏输入的值。
您可以使用json_encode首先通过PHP对发布变量进行编码。然后根据JSON编码的post变量创建一个JS对象(数组)。然后使用JavaScript循环操作这些变量...像-在下面的示例中-填充HTML表单表单:
<script>
<?php $post_vars_json_encode = json_encode($this->input->post()); ?>
// SET POST VALUES OBJECT/ARRAY
var post_value_Arr = <?php echo $post_vars_json_encode; ?>;// creates a JS object with your post variables
console.log(post_value_Arr);
// POPULATE FIELDS BASED ON POST VALUES
for(var key in post_value_Arr){// Loop post variables array
if(document.getElementById(key)){// Field Exists
console.log("found post_value_Arr key form field = "+key);
document.getElementById(key).value = post_value_Arr[key];
}
}
</script>
一种选择是在PHP中设置cookie。
例如:一个名为invalid的cookie ,其值$invalid在1天后到期:
setcookie('invalid', $invalid, time() + 60 * 60 * 24);
然后在JS中读取它(使用JS Cookie插件):
var invalid = Cookies.get('invalid');
if(invalid !== undefined) {
Cookies.remove('invalid');
}
现在,您可以从invalidJavaScript中的变量访问值。
这取决于您定义为JavaScript的内容。如今,实际上我们在诸如NodeJS之类的服务器端程序中都有JS。它与您在浏览器中编码的JavaScript完全相同,例如作为服务器语言。因此,您可以执行以下操作:(Casey Chu的代码: https ://stackoverflow.com/a/4310087/5698805)
var qs = require('querystring');
function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
var post = qs.parse(body);
// use post['blah'], etc.
});
}
}
并由此使用post['key'] = newVal;等...
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");
$(function(){
$('form').sumbit{
$('this').serialize();
}
});
在jQuery中,上面的代码将为您提供URL字符串以及URL中的POST参数。提取POST参数并非不可能。
要使用jQuery,您需要包括jQuery库。为此,请使用以下命令:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>