ajax学习笔记2-JSON形式返回(大拇指向上)

2021-07-15 23:06

阅读:724

YPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

标签:作用域   名称   server   长度   url   false   height   set   each   

JSON:

JavaScript对象标记法,JavaScript Object Notation

存储和交换文本信息的语法,类似XML。采用键值对的方式来组织,易于阅读与编写,同时易于机器解析和生成。

任何语言都可以解析json

 

JSON与XML比较:

JSON的长度更短;读写速度更快;可以使用JavaScript内建的方法直接进行解析,转换成JavaScript对象,方便。

 

JSON语法:

数据书写格式:名称/值对

名称/值对组合中的名称写在前面(在双引号中),值对写在后面(双引号中),中间用冒号隔开。如”name”:”xt”

json的值类型:

数字、字符串、逻辑值、数组、对象、null

 

 

JSON的解析方法:

eval(不推荐)、JSON.parse()(可以检测出语法错误)        

在线JSON校验工具:JSONLinnt,地址:jsonlint.com

可以直接在chrome的检查模式的console下测试

 

var jsondata=‘{"staff":[{"name":"s","age":"2"},{"name":"d","age":"6"},{"name":"k","age":"9"}]}‘;

var jsonObj=eval(‘ (‘+jsondata+‘)‘);

alert(jsonObj.staff[0].name);                  

 

 

var jsondata=‘{"staff":[{"name":"s","age":"2"},{"name":"d","age":"6"},{"name":"k","age":"9"}]}‘;

var jsonObj=JSON.parse(jsondata);

alert(jsonObj.staff[0].name);

 

设置服务器端以json字符串的形式返回响应:

代码实现demo1.html:

>

Demo

 body,input,button,select,h1{

 font-size:26px;

 line-height:1.8;

 }

 

员工查询

 

员工创建



 

 



 

document.getElementById("search").onclick=function(){

   //发送ajax查询请求并处理

   var request=new XMLHttpRequest();

   request.open("GET","service1.php?number="+document.getElementById("keyword").value);

   request.send(); 

   request.onreadystatechange=function(){

if(request.readyState===4){

            if(request.status===200){

               var data=JSON.parse(request.responseText);

               //解析服务器端返回的json字符串

               if(data.success){  //如果json对象的success为true,则返回msg

document.getElementById("searchResult").innerHTML=data.msg;

 }else{                     

  document.getElementById("searchResult").innerHTML="出现错误:"+data.msg;               }

        }else{

  alert("发生错误:"+request.status); 

}

}  

  }

}

 

document.getElementById("save").onclick=function(){

   //发送ajax查询请求并处理

   var request=new XMLHttpRequest();

   request.open("POST","service1.php");

   var data="name="+document.getElementById("staffName").value

         +"&number="+document.getElementById("staffNumber").value

             +"&sex="+document.getElementById("staffSex").value

+"&job="+document.getElementById("staffJob").value;

//参数之间用&隔开

   request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

   request.send(data);  //传入创建员工时各个输入框中输入的数据

   request.onreadystatechange=function(){

 if(request.readyState===4){

 if(request.status===200){

var data=JSON.parse(request.responseText);

                  //解析服务器端返回的json字符串

                  if(data.success){  //如果json对象的success为true,则返回msg                                  document.getElementById("createResult").innerHTML=data.msg;

                                  }else{                              document.getElementById("createResult").innerHTML="出现错误:"+data.msg;    

}

}else{

       alert("发生错误:"+request.status);

    }

}  

  }

}

 

服务器端代码service1.php:

//设置页面内容是html编码格式是utf-8

//header("Content-Type: text/plain;charset=utf-8");

header("Content-Type: application/json;charset=utf-8");

//header("Content-Type: text/xml;charset=utf-8");

//header("Content-Type: text/html;charset=utf-8");

//header("Content-Type: application/javascript;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是一个超全局变量,在一个脚本的全部作用域中都可用,不用使用global关键字

//$_SERVER["REQUEST_METHOD"]返回访问页面使用的请求方法

if ($_SERVER["REQUEST_METHOD"] == "GET") {

                                                                   search();

} elseif ($_SERVER["REQUEST_METHOD"] == "POST"){

                                                                   create();

}

 

//通过员工编号搜索员工

function search(){

                                                                   //检查是否有员工编号的参数

                                                                   //isset检测变量是否设置;empty判断值为否为空

                                                                   //超全局变量 $_GET 和 $_POST 用于收集表单数据

                                                                   if (!isset($_GET["number"]) || empty($_GET["number"])) {

                                                                            echo ‘{"success":false,"msg":"参数错误"}‘;

                                                                            return;

                                                                   }

                                                                   //函数之外声明的变量拥有 Global 作用域,只能在函数以外进行访问。

                                                                   //global 关键词用于访问函数内的全局变量

                                                                   global $staff;

                                                                   //获取number参数

                                                                   $number = $_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;

                                                                   }

                                                                   //TODO: 获取POST表单数据并保存到数据库

                                                                  

                                                                   //提示保存成功

                                                                   echo ‘{"success":true,"msg":"员工:‘. $_POST["name"].‘信息保存成功!"}‘;

}

 

ajax学习笔记2-JSON形式返回(大拇指向上)

标签:作用域   名称   server   长度   url   false   height   set   each   

原文地址:http://www.cnblogs.com/haimengqingyuan/p/7071911.html


评论


亲,登录后才可以留言!