1. Ajax basic syntax
<script> $(function(){ $('#sub').click(function(){ var username=$('#username').val(); var password = $ ('# password'). val (); $.ajax({ type: "post", url: "http://xxx/test/demo.php", data: {username:username,password:password}, //Data submitted to demo.php dataType: "json", //The data format of the data received by the callback function success: function(msg){ $('#text').empty(); //Empty all content in Text var data = ''; if(msg!=''){ data = eval("("+msg+")"); //parse the returned json data and assign it to data } $('#text').html("Username: " + data.username + ", Password: " + data.password); //Output in #text console.log(data); //console output }, error:function(msg){ console.log(msg); } }); }); }) </script>
2. Receive method on the php side
<!--?php header('Content-type:text/json;charset=utf-8'); $username=$_POST['username']; $password=$_POST['password']; $data='{username:"' . $username . '",password:"' . $password .'"}';//Combined into json format data echo json_encode($data);//Output json data ?>
3.html Hatshiro 码 demo.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajaxTest</title> </head> <body> <input type="text" id="username"> <input type="text" id="password"> <button id="sub">查询</button> <span id="text"></span><!-- to display the returned data, only refresh this part--> </body> <script src="//cdn.bootcss.com/jquery/3.0.0-alpha1/jquery.min.js"></script> </html>