2012-05-17 59 views
0

我正在學習php和html。Html表單onsubmit在窗體中編輯文本字段?

我想按下一個提交按鈕時運行一個函數。然後,我希望它使用該函數的變量編輯窗體上的文本字段。不需要換一個新的頁面......就像自刷新一樣。

我該怎麼做?謝謝。

我想我已經看到如何使用JavaScript 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; 
} 
?> 
+1

添加以下代碼看看一些Ajax教程 - 應該讓你開始。 – jprofitt

回答

0

這樣的:

// 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... 
+0

這工作!謝謝,與ajax替代品相比很簡單。如果它是新鮮的加載,雖然$變量未聲明,並出現錯誤字段...什麼是解決這個問題的最好方法? –

+0

固定。我關掉了這個警告,並添加了一個數組,該數組不會偶然碰到其他具有相同名稱的變量。 – ShaaD

+0

這不再有效。如果我刪除它的@符號。如果我甚至沒有點擊它不。 –

0

使用ajax得到從PHP文件的密碼,並更新文本框。

使用jquery和AJAX一些示例代碼:

$.ajax({ 
url : 'ajax.php', 
type : 'post', 
success : function(data){ 
$('#password_field').val(data)   
} 
}); 
0
$.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. 
0

使一個單獨的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>