开发者

Get value of HTML element within PHP on same page?

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:

page1.php

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

page2.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 clic开发者_如何学Cking a submit button?


With 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-jQuery IE doesn't have the XMLHttpRequest object so here is a shim for 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.");
};


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

You use JavaScript for that.

document.form1.input1.value
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜