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 인 스 턴 스 코드 를 전달 하 는 것 입 니 다.여러분 께 도움 이 되 셨 으 면 좋 겠 습 니 다.궁금 한 점 이 있 으 시 면 메 시 지 를 남 겨 주세요.편집장 님 께 서 바로 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Javascript Ajax에 대한 간단한 연습저는 약 4년 동안 프로그래밍 개인 튜터로 일한 경험이 있습니다. 약 5년 전에 " "이라는 제목의 페르시아어로 내 웹사이트에 블로그 게시물을 올렸고 사람들이 저에게 전화하기 시작했습니다. 나는 항상 사람들을 가르치...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.