[英]Html form onsubmit edit a text field in the form?
我正在学习php和html。
我试图在按下提交按钮时使函数运行。 然后,我希望它使用该函数的变量来编辑表单上的文本字段。 无需进入新页面...就像自我刷新一样。
我该怎么做呢? 谢谢。
我想我已经看过如何使用JavaScript getelementbyID
做到这getelementbyID
。 但是我需要通过php来做。
可能是一种简单的解释方法:按下按钮时,它将在文本字段中自动生成一个密码。
我正在使用的功能:
<?
function genkey($length){
$key = '';
list($usec, $sec) = explode(' ', microtime());
mt_srand((float) $sec + ((float) $usec * 100000));
$possibleinputs = array_merge(range('z','a'),range(0,9),range('A','Z'));
for($i=0; $i<$length; $i++) {
$key .= $possibleinputs{mt_rand(0,61)}; }
return $key;
}
?>
使用ajax从php文件获取密码并更新文本字段。
一些使用jquery和ajax的示例代码:
$.ajax({
url : 'ajax.php',
type : 'post',
success : function(data){
$('#password_field').val(data)
}
});
$.ajax({
url: "/your_php_page/function",
type: "POST",
data: "parameters you want to post to the function",
success: function(data){
$('#input_field_to_be_updated').val(data);
}
});
Your php function should be echoed the password which you want to place it in input box.
像这样:
// index.php
<?php
function genkey($length){
$key = '';
list($usec, $sec) = explode(' ', microtime());
mt_srand((float) $sec + ((float) $usec * 100000));
$possibleinputs = array_merge(range('z','a'),range(0,9),range('A','Z'));
for($i=0; $i<$length; $i++) {
$key .= $possibleinputs{mt_rand(0,61)}; }
return $key;
}
$data = array();
if( !empty($_POST['variable']) ) {
$data['variable'] = genkey( strlen($_POST['variable']) );
} else {
$data['variable'] = '';
}
?>
//...HTML...
<form action="" method="POST">
<input name="variable" value="<?=$data['variable']?>">
<input type="submit" value="toPHP">
</form>
//...HTML...
使用该功能制作一个单独的php文件(keygen.php)。
<?php
$length=$_GET['klength'];
echo genkey($length);
function genkey($length){
$key = '';
list($usec, $sec) = explode(' ', microtime());
mt_srand((float) $sec + ((float) $usec * 100000));
$possibleinputs = array_merge(range('z','a'),range(0,9),range('A','Z'));
for($i=0; $i<$length; $i++) {
$key .= $possibleinputs{mt_rand(0,61)}; }
return $key;
}
?>
比在您的html文件中添加此代码
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$.get('keygen.php?length=32', function(data) {
alert(data)
});
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.