简体   繁体   中英

read parameters from url using POST method in javascript

I read somewhere in this forum that I can create a form using javascript like this:

<a href="#" onclick="postLogin()">Log me into this website</a>

<script type="text/javascript">
function postLogin() {
    var form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action", "index2.html");

    var params = {checktype: 'uid', user: 'adam', password: 'pass1234', profile: 'dart', defaultdb: 'kts'};
    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}
</script>

In this form, it using POST method and will navigate to index2.html . And in my index2.html , I need these parameters like checktype , user , password to continue process something. How can I read these parameters in index2.html . I already tried something like:

   <script>
                var query = window.location.search;
                .....
    </script>

in my index2.html but the return query showed nothing. I think it's because that in the POST method, no parameters included in the url so I can not read them using window.location.search . Can anyone have an idea how can I read the parameters sending using the POST method?

If you want to develop a dynamic web application you should use a server side language (to generate html). Basically yes you can access to query params with javascript.

You can define a function in your index2.html:

function getQueryParam ( name , queryString ) {
    var match = RegExp( name + '=([^&]*)' ).exec( queryString || location.search );
    return match && decodeURIComponent( match[ 1 ] );
}

and again in your index2.html use this function to access the parameter you want (for example for parameter 'checkType'):

getQueryParam('checkType')

Of course these should be in 'script' tag.

You can't.

Data from the request body is not made available to client side JavaScript by the browser.

You can read it only using server side code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM