将随机唯一字符串添加到输入值,并实时显示结果


Add random unique string to input value, and display the result live?

我正在尝试在没有注册的情况下建立唯一的用户名,这最终可能会使用相同的用户名,我不能说"查看该用户的所有帖子",因为用户可以具有相同的名称。

基本上我正在使用这个名为"用户提交帖子"的wordpress插件,这很棒,因为用户无需注册即可发布文章,但是存在重复名称问题,因此我认为解决方案可能是我们有一个输入字段:

<input name="user-submitted-name" type="text" value="" data-required="true" required placeholder="Your name" class="form-control input-lg usp-input">

我们在输出中添加一个随机的唯一字符串,以便:

User 1: simon_xyz
User 2: simon_abc

我想在 php 中生成随机字符串非常简单,找到了很多对我有帮助的堆栈,例如这个问题: PHP 随机字符串生成器

但理想情况下,我想告诉用户"这是您的用户名,复制它并始终使用它"。由于没有注册,因此不会有电子邮件要求,那么如何将随机唯一字符串添加到输入字段值并实时显示结果?

我正在使用这个jQuery将复选框的值添加到网站上其他内容的输入字段中:

            $('.checkTag').click(function() {
                $("#user-submitted-tags").val(
                    $('.checkTag:checked').map(function() {
                            return $(this).val();
                    }).get().join(', ')
                );
        });

也许可以使用这样的东西,但我正在努力,因为随机字符串不是您会选择的。

实时结果如下所示:

<h2>This is your username</h2>
<h3>Use this user name the next time you write your post</h3>
<p>Your usernanme is: simon_xyz</p>

据我现在了解,根据您的评论,我会提出这样的事情:

带有用户名输入框的页面(省略<head><html><body>)(基于问题中的 JS-代码段,我假设您可以使用 jQuery):

$uniqueRandomString = ...;
?>
<form id="username-form"> (or get, that doesn't really matter, just remember to adjust it on the processing page.)
    <input type="text" name="username" id="username-input" /> <? echo "+ " . $uniqueRandomString; ?>
    <input type="hidden" name="unique-random-string" value="<? echo $uniqueRandomString; ?>"/>
    <input type="submit" />
</form>
<script>
    $("#username-form").on('submit', function() { // Of course you could change the ID of the form, but you'll have to change this as well in that case.
        $.get('url/of/processing/page.php?' + $(this).serialize(), function(data) {
            if (data.indexOf("SUCCESS") == 0) {
                username = data.substring(8);
                $('body').append("<h2>This is your username</h2>
                                  <h3>Use this user name the next time you write your post</h3>
                                  <p>Your usernanme is: " + username + "</p>");
            } else {
                // Display an error message.
            }
        });
    });

您处理用户名的页面:

<?
// Check if the unique random string - now contained is $_POST['unique-random-string'] - is valid!
// If not, make the expression in this if-statement evaluate to true.
if ($error) echo "ERROR";
else echo "SUCCESS:" . $_GET['username'];
?>