单击文本标记以生成新哈希

时间:2017-05-17 08:27:27

标签: php jquery html ajax

$num = rand(0, 10000);
$hash = password_hash($num, PASSWORD_BCRYPT, array(
    'cost' => 6
));

上面是哈希

<p class="reg-code">Hash: <span><?php echo $hash; ?></span><i class="fa fa-refresh" aria-hidden="true" id="refresh-code"></i></p>

我希望如此,当有人点击标签时它会在跨度中生成一个新的哈希,我怎么会遇到这个?

我不确定如何做到这一点,比如PHP中的函数或者什么。

3 个答案:

答案 0 :(得分:0)

它叫做Ajax:

<p class="reg-code">
  Hash: 
  <span id="hash"><?php echo $hash; ?></span>
  <i id="click" class="fa fa-refresh" aria-hidden="true" id="refresh-code"></i>
</p>

$('#click').click(function(){
  $.post( "./path/to/hashscript.php", function( data ) {
    $( "#hash" ).html( data );
  });
});

您使用JavaScript事件发出服务器请求并使用响应更新页面元素。您的PHP脚本应该回显$hash

echo password_hash($num, PASSWORD_BCRYPT, ['cost' => 6]);

答案 1 :(得分:0)

  

Ajax允许您在不刷新的情况下将请求发送到另一个页面。   检查jQuery Perform an asynchronous HTTP (Ajax) request

的这一部分

在你的情况下,你设置如下(第1,在页面的头部包含jQuery):

<p class="reg-code">Hash: <span></span>
<i class="fa fa-refresh" aria-hidden="true" id="refresh-code"></i></p>

请注意&lt; span&gt;处理响应是空的(但可以在开头显示原始哈希值。当你点击链接时,它的内容将被替换)当我们开始时,并且有一个ID附加到刷新链接

然后,您使用jQuery:

$(document).ready( function() {
    $("#refresh-code").click(function(){ // click on element with ID 'refresh-code'

    $.ajax({ // method default is 'GET'
           url: "hash.exe.php", // the PHP page that will generate new hash
           success: function(html){ // if no PHP error 'html' is the response
                    $(".reg-code > span").html(html); // we append the html in the span
            },
            error: function (request, status, error) { // we handle error
            alert(request.responseText);
            }
          });
    });
});

PHP(hash.exe.php)看起来像这样(让你按原样处理,添加echo的答案):

<?php
error_reporting(E_ALL); ini_set('display_errors', 1);

$num = rand(0, 10000);
$hash = password_hash($num, PASSWORD_BCRYPT, array(
'cost' => 6
));

echo"$hash"; // this 'invisible' HTML output is echo'd back to the page who initiated it
?>
  

将所有内容放在一起的示例FIDDLE

答案 2 :(得分:0)

应该得到。因为它不会改变服务器状态。只需返回新值。

$('.fa-refresh').click(function(){
   $.get( "./path/to/hashscript.php", function( data ) {
    $( ".reg-code > span" ).html( "Hash:" + data );
   });
});

和hashscript.php文件应该包含

echo md5(uniqid(rand(), TRUE));