Home >Backend Development >PHP Tutorial >php+jQuery+Ajax simply implements asynchronous page refresh_php example

php+jQuery+Ajax simply implements asynchronous page refresh_php example

WBOY
WBOYOriginal
2016-08-17 13:02:321259browse

The page is displayed as follows:

The code in JQueryAjax.html is as follows (using the simpler $.post)

<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

<&#63;php 
echo '用户名:',$_POST['name'],',密码:',$_POST['pwd']."<br>";
//这里可以进行一些操作,比如数据库交互


echo "操作完毕";
&#63;>

In non-json format, the background can only return strings. If you want to return an array in the background, you can use json format

For example, modify the code in JQueryAjax to the following form:

<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

<&#63;php 
$name = $_POST['name'];
$pwd = $_POST['pwd'];
$array = array("$name","$pwd");
//这里进行一个些操作,比如数据库交互

echo json_encode($array);//json_encode方式是必须的
&#63;>

The operation effect is as follows:

The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope that everyone will support Script Home.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn