How to retrieve GET or POST via JavaScript?
How to retrieve get or post via javascript only? and not php. 开发者_StackOverflow中文版
Is it possible?
Obviously you cannot read POST data using javascript because data is POSTed in the body of the HTTP request and only a server side script is capable of reading it. As far as GET data is concerned you could use this function to parse the query string of the current page:
function gup(name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec(window.location.href);
if(results == null) {
return "";
}
return results[1];
}
and use like this:
var username = gup('username');
To extract the values of the querystring from the URL, you may want to check out this solution by @CMS in another Stack Overflow post.
However, JavaScript has no access to the HTTP request to which it was served. One possible option is to render JavaScript code from your server-side script in such a way to pass all/some POST values to JavaScript. Very basic example using php:
<script type="text/javascript>
var postValue = '<?php echo $_POST["name"]; ?>';
</script>
In addition to the above, you could also use the json_encode
function like this to serialize all the POST data to a JavaScript object (hash table):
<script type="text/javascript>
var postData = <?php echo json_encode($_POST); ?>;
</script>
Then in JavaScript you should be able to access all your POST data as follows:
alert(postData["name"]); // displays the value of name
If you use GET then Javascript can read the values that are passed using window.location.search.
See http://javascript.about.com/library/blqs1.htm for more info on how to do it.
Javascript has no access if you use POST
Javascript works on the client machine. POST is send from the client machine to the server.
So, you are left with the query string only.
精彩评论