页面显示如下:
jqueryajax.html中的代码如下(用的较为简单的$.post)
php" id="highlighter_495032">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<html> <head> <meta charset= "utf-8" > <title>jqueryajax+php</title> <script type= "text/javascript" src= "https://code.jquery.com/jquery-3.0.0.min.js" ></script> </head> <body> 用户名:<input type= "text" id= "username" name= "username" /><br> 密码:<input type= "password" id= "password" name= "password" /><br> <button type= "button" class = "butn" >ajax提交</button><br> <span class = "con" ></span> <script type= "text/javascript" > $(document).ready( function (){ $( ".butn" ).click( function (){ var username = $( "#username" ).val(); var password = $( "#password" ).val(); $.post( 'ajax.php' ,{name:username,pwd:password}, function (data) { alert(data); $( ".con" ).html(data); }) }) }) </script> </body> </html> |
ajax.php
1
2
3
4
5
6
7
|
<?php echo '用户名:' , $_post [ 'name' ], ',密码:' , $_post [ 'pwd' ]. "<br>" ; //这里可以进行一些操作,比如数据库交互 echo "操作完毕" ; ?> |
在非json格式下,后台只能返回字符串,如果想后台返回数组,可以采用json格式
例如将jqueryajax中的代码修改为如下形式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
<html> <head> <meta charset= "utf-8" > <title>jqueryajax+php</title> <script type= "text/javascript" src= "https://code.jquery.com/jquery-3.0.0.min.js" ></script> </head> <body> 用户名:<input type= "text" id= "username" name= "username" /><br> 密码:<input type= "password" id= "password" name= "password" /><br> <button type= "button" class = "butn" >ajax提交</button><br> <span class = "con" ></span> <script type= "text/javascript" > $(document).ready( function (){ $( ".butn" ).click( function (){ var username = $( "#username" ).val(); var password = $( "#password" ).val(); $.ajax({ url: "ajax.php" , type: "post" , data:{name:username,pwd:password}, datatype: "json" , error: function (){ alert( 'error loading xml document' ); }, success: function (data,status){ //如果调用php成功 alert(status); alert(data); $( '.con' ).html( "用户名:" +data[0]+ "密码:" +data[1]); } }); }) }) </script> </body> </html> |
ajax.php
1
2
3
4
5
6
7
8
|
<?php $name = $_post [ 'name' ]; $pwd = $_post [ 'pwd' ]; $array = array ( "$name" , "$pwd" ); //这里进行一个些操作,比如数据库交互 echo json_encode( $array ); //json_encode方式是必须的 ?> |
运行效果如下:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。