在同一页面上获取 PHP 中 HTML 元素的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7410322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:38:09  来源:igfitidea点击:

Get value of HTML element within PHP on same page?

phphtml

提问by user617123

In the past, whenever I needed to get the value of an html element, I would always submit a form to load a different page. Something like:

过去,每当我需要获取 html 元素的值时,我总是提交一个表单来加载不同的页面。就像是:

page1.php

页面1.php

<form name="form1" action="page2.php" method="post">
   <input type="hidden" name="input1" value="value1" />
</form>

page2.php

页面2.php

<?php
   $data = $_POST['input1'];
?>

My question is, is it possible to get the value of 'input1' on the same page (page1.php) without requiring clicking a submit button?

我的问题是,是否可以在同一页面 (page1.php) 上获取 'input1' 的值而无需单击提交按钮?

回答by Joe

With jQuery:

使用jQuery

<?php 
    if (isset($_POST['data'])) { 
        $data = $_POST['data']; 
        print( "data is: $data" ); 
        return; 
    } 
?> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<script type="text/javascript" src="jquery-1.6.3.js"></script> 
</head> 
<body> 

<div>Response from server: <span id="response"></span></div> 
<script type="text/javascript"> 
    $.post('test.php',{'data': "value1"}, function (data) {
        $('#response').text(data);
    }); 
</script> 
</body> 
</html>

Non-jQueryIE doesn't have the XMLHttpRequest object so here is a shim for IE:

非 jQueryIE 没有 XMLHttpRequest 对象,所以这里是 IE 的垫片:

Yes, using ajax / javascript:

var formData = new FormData();

formData.append("input1", "value1");

var xhr = new XMLHttpRequest();
xhr.open("POST", "page1.php");
xhr.send(formData);

if (typeof XMLHttpRequest == "undefined") XMLHttpRequest = function() {
    try {
        return new ActiveXObject("Msxml2.XMLHTTP.6.0");
    }
    catch (e) {}
    try {
        return new ActiveXObject("Msxml2.XMLHTTP.3.0");
    }
    catch (e) {}
    try {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e) {}
    //Microsoft.XMLHTTP points to Msxml2.XMLHTTP and is redundant
    throw new Error("This browser does not support XMLHttpRequest.");
};

回答by Rolando Cruz

What for? Do you want to submit it to another file without needing to actually "submit" the form?

做什么的?您是否想将其提交到另一个文件而无需实际“提交”表单?

You use JavaScript for that.

您为此使用 JavaScript。

document.form1.input1.value