Ajax JSON 인 스 턴 스 코드 전달

앞 말
ajax 는 모두 asynchronous javascript and XML 이 라 고 하지만.그러나 현재 ajax 기술 을 사용 할 때 JSON 을 전달 하 는 것 은 사실상 의 기준 이 되 었 다.XML 에 비해 JSON 은 간단 하면 서도 편리 하기 때문이다.본 고 는 전편 의 실례 를 고 쳐 쓰 고 JSON 의 방식 으로 데이터 전달 을 할 것 이다
전단 페이지

<!--      -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body{font-size: 20px;margin: 0;line-height: 1.5;}
select,button,input{font-size: 20px;line-height: 1.5;}
</style>
</head>
<body>
<h2>    </h2>  
<label>       :</label>
<input type="text" id="keyword">
<button id="search">  </button>
<p id="searchResult"></p>
<h2>    </h2>
<form id="postForm">
  <label>       :</label>
  <input type="text" name="name"><br>
  <label>       :</label>
  <input type="text" name="number"><br>
  <label>       :</label>
  <select name="sex">
  <option value=" "> </option>
  <option value=" "> </option>
  </select><br>
  <label>       :</label>
  <input type="text" name="job"><br>
  <button id="save" type="button">  </button>  
</form>
<p id="createResult"></p>
<script>
/*get*/
//  
var oSearch = document.getElementById('search');
//get      
function addURLParam(url,name,value){
  url += (url.indexOf("?") == -1 ? "?" : "&");
  url +=encodeURIComponent(name) + "=" + encodeURIComponent(value);
  return url;
}
oSearch.onclick = function(){
  //  xhr  
  var xhr;
  if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
  }else{
    xhr = new ActiveXObject('Microsoft.XMLHTTP');
  }
  //      
  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
      if(xhr.status == 200){
        //    
        var data = JSON.parse(xhr.responseText);
        if(data.success){
          document.getElementById('searchResult').innerHTML = data.msg;
        }else{
          document.getElementById('searchResult').innerHTML = '    :' +data.msg;
        }
      }else{
        alert('    :' + xhr.status);
      }
    }
  }
  //    
  var url = 'service.php';
  url = addURLParam(url,'number',document.getElementById('keyword').value);
  xhr.open('get',url,true);
  xhr.send();
}
/*post*/
//  
var oSave = document.getElementById('save');
//post      
function serialize(form){    
  var parts = [],field = null,i,len,j,optLen,option,optValue;
  for (i=0, len=form.elements.length; i < len; i++){
    field = form.elements[i];
    switch(field.type){
      case "select-one":
      case "select-multiple":
        if (field.name.length){
          for (j=0, optLen = field.options.length; j < optLen; j++){
            option = field.options[j];
            if (option.selected){
              optValue = "";
              if (option.hasAttribute){
                optValue = (option.hasAttribute("value") ? option.value : option.text);
              } else {
                optValue = (option.attributes["value"].specified ? option.value : option.text);
              }
              parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(optValue));
            }
          }
        }
        break;       
      case undefined:   //fieldset
      case "file":    //file input
      case "submit":   //submit button
      case "reset":    //reset button
      case "button":   //custom button
        break;        
      case "radio":    //radio button
      case "checkbox":  //checkbox
        if (!field.checked){
          break;
        }
        /* falls through */
      default:
        //don't include form fields without names
        if (field.name.length){
          parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value));
        }
    }
  }    
  return parts.join("&");
}
oSave.onclick = function(){
  //  xhr  
  var xhr;
  if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
  }else{
    xhr = new ActiveXObject('Microsoft.XMLHTTP');
  }
  //      
  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
      if(xhr.status == 200){
        //    
        var data = JSON.parse(xhr.responseText);
        if(data.success){
         document.getElementById('createResult').innerHTML = data.msg; 
       }else{
         document.getElementById('createResult').innerHTML = '    :'+data.msg;
       }
      }else{
        alert('    :' + xhr.status);
      }
    }
  }
  //    
  xhr.open('post','service.php',true);
  xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
  xhr.send(serialize(document.getElementById('postForm')));
}
</script>
</body>
</html>
백 엔 드 페이지

<?php 
//          
function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
//       html     utf-8
header("Content-Type:application/json;charset=utf-8");
//        ,       ,           
$staff = array(
  array("name"=>"  ","number"=>"101","sex"=>" ","job"=>'   '),
  array("name"=>"  ","number"=>"102","sex"=>" ","job"=>'     '),
  array("name"=>"  ","number"=>"103","sex"=>" ","job"=>'    ')
  );
//     get  ,     ;   POST  ,     
//$_SERVER["REQUEST_METHOD"]             
if($_SERVER["REQUEST_METHOD"] == "GET"){
  search();
}else if($_SERVER["REQUEST_METHOD"] == "POST"){
  create();
}
//          
function search(){
  //            
  //isset        ;empty       
  if(!isset($_GET['number']) || empty($_GET['number'])){
    echo '{"success":false,"msg":"    "}';
    return;
  }
  global $staff;
  $number = test_input($_GET['number']);
  $result = '{"success":false,"msg":"      "}';
  //  $staff    ,  key  number       。    ,       
  foreach($staff as $value){
    if($value['number'] == $number){
      $result = '{"success":true,"msg":"    :     ' .$value["number"] .',     ' .$value["name"] .',     ' .$value["sex"] .',     ' .$value["job"] .'"}';
      break;
    }
  }
  echo $result;
}
//    
function create(){
  //          
  if(!isset($_POST['name']) || empty($_POST['name']) || 
    !isset($_POST['number']) || empty($_POST['number']) ||
    !isset($_POST['sex']) || empty($_POST['sex']) ||
    !isset($_POST['job']) || empty($_POST['job']) 
    ){
    echo '{"success":false,"msg":"    ,        "}';
    return;
  }
  echo '{"success":true,"msg":"  ' .test_input($_POST['name']) .'      !"}';
}
?>
실례 시범

위 에서 말 한 것 은 편집장 님 께 서 소개 해 주신 Ajax 가 JSON 인 스 턴 스 코드 를 전달 하 는 것 입 니 다.여러분 께 도움 이 되 셨 으 면 좋 겠 습 니 다.궁금 한 점 이 있 으 시 면 메 시 지 를 남 겨 주세요.편집장 님 께 서 바로 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기