I am using jQuery+JSON combination something like this:
test.php:
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'></div>
_test.php:
<?php
// Code here to deal with your form submitted data.
$arr = array( 'testDiv' => 'Form is successfully submitted.' );
echo json_encode( $arr );
?>
jsFile.js:
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
Now what i want is that when a successful form is submitted then without any page refresh a message should be displayed under the div testDiv. I was hoping that this script would help but when a form is submitted then the page goes to .../_test.php and displays the following -
{"testDiv":"Form is successfully submitted."}
Please help.Thanks in advanvce
Is it just me or does this script work for anyone else? I have the three files as detailed above with the addition of the normal doctype and jquery core in the head in the test.php file and I get the success message without any page redirection.
I think I may have got it or at least I got the same symptoms.
You need to check and make sure you load your jquery file in the script tag before jsFile.js
script tag.
BAD
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script type="text/javascript" src="jsFile.js"></script>
<script type="text/javascript" src="../../_api/jquery-1.4.2.js"></script>
</head>
<body>
<form action='_test.php' method='post' class='ajaxform'>
<label>
<input type='text' name='txt' value='Test Text'>
</label>
<input type='submit' value='submit'>
</form>
<div id='testDiv'></div>
</body>
</html>
GOOD
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script type="text/javascript" src="../../_api/jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
</head>
<body>
<form action='_test.php' method='post' class='ajaxform'>
<label>
<input type='text' name='txt' value='Test Text'>
</label>
<input type='submit' value='submit'>
</form>
<div id='testDiv'></div>
</body>
</html>
Your JSON string is a bit wrong, you would need it to return:
{"id":"testDiv","message":"Form is successfully submitted."}
Then in the response:
for(var id in data) { jQuery('#' + data.id).html( data.message ); }
为什么不只有带有单击事件的普通按钮而不是提交按钮呢?
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.