index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <Meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Ajax</title> <script type="text/javascript" src="jquery-1.10.1.js"></script> <script type="text/javascript" src="demo.js"></script> <link type="text/css" rel="stylesheet" href="style.css" /> </head> <body> <!-- <input type="button" value="异步加载数据" /> <div id="Box"></div> <form> 用户名:<input type="text" name="user" /> 邮件:<input type="text" name="email" /> <input type="button" value="提交" /> </form> <div id="Box"></div> --> <form> 用户名:<input type="text" name="user" /> 邮件:<input type="text" name="email" /> <input type="radio" name="sex" value="男" />男 <input type="radio" name="sex" value="女" />女 <input type="button" value="提交" /> </form> <div id="Box"></div> </body> </html>
test.PHP
<?PHP if($_POST['url'] == 'onestopweb'){ echo '一站式建网站'; }else{ echo '不存在'; } ?>
user.PHP
<?PHP echo $_POST['user'].'-'.$_POST['email'] ?>
demo.js
$(function(){ /* $('input').click(function(){ $.ajax({ type:'POST',url:'test.PHP',data:{ url:'onestopweb' },success:function(response,status,xhr){ $('#Box').html(response); } }); }); $('form input[type=button]').click(function(){ $.ajax({ type:'POST',url:'user.PHP',data:{ user:$('form input[name=user]').val(),email:$('form input[name=email]').val() },xhr){ $('#Box').html(response); } }); }); //表单元素特别多的情况下,写起来非常麻烦,容易出错 //复制提交的 JS 内容时, data 属性需要修改的非常多 $('form input[type=button]').click(function(){ $.ajax({ type:'POST',data:$('form').serialize(),xhr){ $('#Box').html(response); } }); }); alert($('form').serialize());//字符串形式的键值对,并且还对 URL 进行的编码 $('form input[name=sex]').click(function(){ //$('#Box').html($(this).serialize()); $('#Box').html(decodeURIComponent($(this).serialize())); }); $('form input[name=sex]').click(function(){ //console.log($(this).serializeArray()); var json = $(this).serializeArray(); $('#Box').html(json[0].name +'='+json[0].value); }); //初始化重复的属性 $.ajaxSetup({ type:'POST',data:$('form').serialize() }); $('form input[type=button]').click(function(){ $.ajax({ success:function(response,xhr){ $('#Box').html(response); } }); }); */ $('form input[type=button]').click(function(){ $.ajax({ type:'POST',data:$.param({ user:$('form input[name=user]').val(),email:$('form input[name=email]').val() }),xhr){ $('#Box').html(response); } }); }); alert($.param({ user:$('form input[name=user]').val(),email:$('form input[name=email]').val() })); });