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

时间:2011-09-14 01:29:16

标签: php html

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

page1.php中

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

使page2.php

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

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

2 个答案:

答案 0 :(得分:4)

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

非jQuery IE没有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.");
};

答案 1 :(得分:3)

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

您可以使用JavaScript。

document.form1.input1.value