如何使用 JavaScript 读取发送请求参数

我试图从我的 HTML 中读取 post 请求参数。我可以使用以下 JavaScript 代码读取 get 请求参数。

$wnd.location.search

但是它不工作的后请求。有人能告诉我如何使用 JavaScript 读取 HTML 中的帖子请求参数值吗?

292455 次浏览

JavaScript 是一个客户端脚本语言,这意味着所有的代码都在 web 用户的机器上执行。另一方面,POST 变量将到达服务器并驻留在那里。浏览器不会向 JavaScript 环境提供这些变量,任何开发人员也不应该期望它们神奇地出现在那里。

因为浏览器不允许 JavaScript 访问 POST 数据,所以如果没有一个像 PHP 这样的外部参与者将 POST 值回显到脚本变量或捕获传输中的 POST 值的扩展/插件,那么读取 POST 变量几乎是不可能的。GET 变量可以通过变通方法获得,因为它们位于客户机机器可以解析的 URL 中。

POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.

$(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>

A little piece of PHP to get the server to populate a JavaScript variable is quick and easy:

var my_javascript_variable = <?php echo json_encode($_POST['my_post'] ?? null) ?>;

Then just access the JavaScript variable in the normal way.

请注意,不能保证任何给定的数据或类型的数据将被张贴,除非你检查-所有的输入字段都是建议,而不是保证。

POST is what browser sends from client(your broswer) to the web server. Post data is send to server via http headers, and it is available only at the server end or in between the path (example: a proxy server) from client (your browser) to web-server. So it cannot be handled from client side scripts like JavaScript. You need to handle it via server side scripts like CGI, PHP, Java etc. If you still need to write in JavaScript you need to have a web-server which understands and executes JavaScript in your server like Node.js

POST variables are only available to the browser if that same browser sent them in the first place. If another website form submits via POST to another URL, the browser will not see the POST data come in.

SITE A: 使用 POST 向外部 URL (SITE B)提交表单 SITE B: will receive the visitor but with only GET variables

可以使用 jQuery-PostCapture (@ssut/jQuery-PostCapture)读取 post 请求参数。

PostCapture 插件由一些技巧组成。

当您单击提交按钮时,onsubmit事件将被发送。

同时,PostCapture 将序列化表单数据并保存到 html5 localStorage (如果可用)或 Cookie 存储中。

Why not use localStorage or any other way to set the value that you 想要通过吗?

这样你就可以从任何地方接触到它!

By 任何地方 I mean 在给定的域/上下文内

<head><script>var xxx = ${params.xxx}</script></head>

<head>中使用 EL 表达式 ${ param.xxx }从 post 方法获取参数,并确保在 <head>之后包含 js 文件,以便您可以直接在 js 文件中处理像‘ xxx’这样的参数。

我们可以使用 连载概念收集使用 POST 提交的表单参数。

试试这个:

$('form').serialize();

只要封闭它的警报,它显示所有的参数,包括隐藏。

您可以“ 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>
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");

一种选择是在 PHP 中设置 cookie。

例如: 一个名为 无效的 cookie,其值 $invalid将在1天内到期:

setcookie('invalid', $invalid, time() + 60 * 60 * 24);

然后用 JS (使用 JS Cookie插件)读出来:

var invalid = Cookies.get('invalid');


if(invalid !== undefined) {
Cookies.remove('invalid');
}

现在可以在 JavaScript 中从 invalid变量访问该值。

使用会话存储!

$(function(){
$('form').submit{
document.sessionStorage["form-data"] =  $('this').serialize();
document.location.href = 'another-page.html';
}
});

在另一个页面. html:

var formData = document.sessionStorage["form-data"];

Reference link - https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

如果您使用的是 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>

It depends of what you define as JavaScript. Nowdays we actually have JS at server side programs such as NodeJS. It is exacly the same JavaScript that you code in your browser, exept as a server language. 所以你可以这样做: (Code by 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;等。

<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>

Or use it to put them in an dictionary that a function could retrieve:

<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>

Then in 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;
}

这只是一个例子,不应该用于 任何敏感数据,如密码等。POST 方法之所以存在是有原因的; 是为了将数据安全地发送到后端,这样就会违背其目的。

但是如果您只是需要一些非敏感的表单数据来访问您的下一个页面,而您的 URL 中没有 /page?blah=value&bleh=value&blahbleh=value,那么这将使您的 URL 更加清晰,并且您的 JavaScript 可以立即与您的 POST 数据进行交互。

我有个简单的密码:

在 index.php 中:

<input id="first_post_data" type="hidden" value="<?= $_POST['first_param']; ?>"/>

在你的主要.js:

let my_first_post_param = $("#first_post_data").val();

因此,当您将 main.js 包含在 index.php (<script type="text/javascript" src="./main.js"></script>)中时,您可以获得包含您的帖子数据的隐藏输入的值。