php+jQuery+Ajax 간단하게 페이지 비동기 리 셋 실현

페이지 는 다음 과 같 습 니 다: 

JQuery Ajax.html 의 코드 는 다음 과 같 습 니 다(비교적 간단 한$.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

<?php 
echo '   :',$_POST['name'],',  :',$_POST['pwd']."<br>";
//          ,       


echo "    ";
?>
비 json 형식 에서 백 엔 드 는 문자열 만 되 돌 릴 수 있 습 니 다.백 엔 드 가 배열 로 돌아 가 려 면 json 형식 을 사용 할 수 있 습 니 다. 
예 를 들 어 JQuery Ajax 의 코드 를 다음 과 같이 수정 합 니 다. 

<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 

<?php 
$name = $_POST['name'];
$pwd = $_POST['pwd'];
$array = array("$name","$pwd");
//         ,       

echo json_encode($array);//json_encode      
?>

실행 효 과 는 다음 과 같 습 니 다:

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기