Ajax通过单击按钮输入的文本中的随机字符

时间:2015-08-04 06:37:34

标签: javascript php ajax

这是随机 PHP 代码:

$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = 5;
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, $charactersLength - 1)];
}//end loop

表格

<form> 
  <input type="text" id="show_random">
  <button onclick="genCode()">gen</button>
</form>

4 个答案:

答案 0 :(得分:1)

使用jQuery

var genCode = function() {
  'use strict';

  $.ajax('/path/to/your/file.php', {
    success: function(response) {
      $('#show_random').val(response);
    }
  });
}

答案 1 :(得分:0)

试试这个

<?php
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $length = 5;
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++)
    {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }//end loop
?>

<form> 
    <input type="text" id"first_textbox">
    <input type="text" id="show_random" value="<?php echo $randomString; ?>">
    <button onclick="genCode()">gen</button>
</form>

答案 2 :(得分:0)

您可以尝试以下脚本:

function genCode() {
    var r = new XMLHttpRequest(); 
        r.open("POST", "index.php", true);
        r.onreadystatechange = function () {
            if (r.readyState != 4 || r.status != 200) return; 
            document.getElementById("show_random").value = r.responseText;
        };
        r.send("");
}

注意:将index.php替换为随机文本的php代码所在的位置。

答案 3 :(得分:0)

不要忘记先包含Jquery lib

    function genCode()
    {
        $.ajax({
            url : '/path/to/your/file.php',
            success: function(response) {
              $('#show_random').val(response);
            }
        });
    }