The jquery POST method is not working?
Here is the html and jQuery part:
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
</head>
<body>
<script type="text/javascript">
$('document').ready(function(){
$('#submit').click(function(){
var username=$('#user').val();
$.pos开发者_如何学Got('http://localhost:8080/verify/comment.php',
{
user:username
},
function(return_data)
{
alert(return_data);
}
);
});
});
</script>
Username:<input type="text" id="user"/>
<input type="button" id="submit" value="submit"/>
</body>
</html>
comment.php
<?php
echo 'welcome';
?>
It displays an empty alert message.. I can't get the value "welcome" in alert message........
Any suggestion.......?Ohhh... my eyes just went crazy rolling by looking at this code. So many things you are doing wrong... Where to start?
- Current jQuery version is 1.6, not 1.3.2.
- Your HTML is not valid. You don't have a form element.
- You don't listen for a
click
event on thesubmit
button, but for asubmit
event on the form.
This should be working for you:
<html>
<head>
</head>
<body>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#login').submit(function(e){
// prevent form submit, so we can do a manual one
e.preventDefault();
var username = $('#user').val();
$.post('http://localhost:8080/verify/comment.php', {user:username}, function(return_data){
alert(return_data.message);
}, 'json');
});
});
</script>
<form id="login" action="" method="post">
<label for="user">Username:</label>
<input type="text" id="user"/>
<input type="button" id="submit" value="submit"/>
</form>
</body>
</html>
Here is your PHP, which echos a json_encode()
d string, for context (notice how we accessed returned_data.message
on the above code:
<?php
$return_data = array(
'message' => 'Welcome'
);
echo json_encode($return_data);
?>
maybe because of SOP(http://en.wikipedia.org/wiki/Same_origin_policy)
you can not get data from same url with different port through ajax.
Cleaned the code up a bit and you might want to look at this post for some tips on using the post function in jquery:
http://web.archive.org/web/20160410111221/http://www.jensbits.com/2009/10/04/jquery-ajax-and-jquery-post-form-submit-examples-with-php/
Also, the other guys had good advice as far as using a newer version of jquery if you can and making sure the code is clean and correct.
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
$(function(){
$('#submit').submit(function(e){
e.preventDefault();
var username=$('#user').val();
$.post('/verify/comment.php',{user:username},function(return_data){
alert(return_data);
});
});
});
</script>
</head>
<body>
<form>
Username:<input type="text" id="user"/>
<input type="button" id="submit" value="submit"/>
</form>
</body>
</html>
精彩评论