开发者

Truly Random String in Javascript Asynchronously

开发者 https://www.devze.com 2023-04-01 03:00 出处:网络
I am using a javascript function to generate a random string: function S4() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1);

I am using a javascript function to generate a random string:

function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}

function guid() {

    /*$.ajax({
        type: "GET",
        url: "uuid.php",
        cache: false,
        success: function(html){
            return html;
        }
    });*/

   return (S4()+S4()+S4()+S4());
}

And I want to make it utilize a php uuid library that I've found, the problem is I need it to run in javascript. I use the guid() function a lot and I've been trying to think of an elegant way of grabbing the uuid, that I request using the ajax object (commented out above). The uuid page that just prints random uuids开发者_StackOverflow社区 each time is sitting locally next to this page. I would not like to make the request synchronous because, like I said, I use it quite a bit and would prefer to not have everything halt every time this thing makes a request. Or perhaps there's a method I could use of jQuery that be as fast and not hinder performance?

I'm not adverse to changing things up a bit, like would the best practice here to acquire a uuid on load? But the number of UUIDs I generate is completely dynamic, and dependent upon the user.

Thank you!


Check the uniqid() function from phpjs.org.


How about adding a callback argument to the guid() function, wherein you can assign a value to something:

function guid(callback) {
    $.ajax({
        type: "GET",
        url: "uuid.php",
        cache: false,
        success: function(html){
            callback(html);
        }
    });
}

var value;

guid(function (result) {
    value = result;
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号