When using Layui to open a new interface, some parameters may be passed, such as the detail page. I will pass a detail ID field as an identifier, and then the JS code of the detail page will request the data through the ID parameter. I tested the following code:

layui.use(['layer'].function () {
    var router = layui.router();
    var id = router.search.id;
});
Copy the code

Perhaps because of my approach, no matter what data I passed, the router.search object was always an empty object {}, so I had to take a different approach.

implementation

Use Windows. The location. The search. The substr (1) to get the strings in the URL parameter, recycling to get regular data, finally we just need to use the getQueryString (” id “) can get the data content of id.

function getQueryString(name) {
    var reg = new RegExp("(^ | &)" + name + "= (/ ^ & *) (& | $)");
    var r = window.location.search.substr(1).match(reg);
    if(r ! =null) {
        return decodeURI(r[2]);
    }
    return ' ';
}
Copy the code

Optimization scheme

Thanks to question’s reminding, URLSearchParams is a very good choice, the specific code is as follows:

url = new URL('https://moas.medusasorcerer.com?a=2&b=1&c=abc')
params = new URLSearchParams(url.search.slice(1))
params.getAll('a')
params.get('c')
Copy the code






In order to achieve the goal, by hook or by crook wrote a lot of redundant code, ha ha ha ~ I am a fool