首页 > 代码库 > ajax学习笔记4-跨域(大拇指向上)

ajax学习笔记4-跨域(大拇指向上)

跨域:

域名的组成:协议  子域名   主域名   端口号   请求资源地址

如http://  www  .  abc.com :  8080  /  scripts/jquery.js

当协议、子域名、主域名、端口号,任意一个不同时,都属于不同域。不同域之间相互请求资源,就算跨域。

如 http://www.abc.com/index.html请求http://www.efg.com/service.php

 

JavaScript同源策略:脚本只能读取和所属文档来源相同的窗口和文档的属性。

 

JavaScript出于安全考虑,不允许跨域调用其他页面的对象。跨域可简单的理解为:因为JavaScript同源策略的限制,a.com域名下的js无法操作b.com或是c.a.com域名下的对象。

 

主域名abc.com,其可能的子域名有:

www.abc.com

bbs.abc.com

beijing.bbs.abc.com

haidian.beijing.bbs.abc.com

 

处理跨域方法:代理、JSONP、XHR2

 

代理:通过在同域名的web服务器端创建一个代理。

如北京服务器域名www.beijing.com,上海服务器域名为www.shanghai.com,可以选择在北京的web服务器的后台www.beijing.com/proxy-sahnghaiservice.php来调用上海服务器www.shanghai.com/service.php的服务,然后再把响应结果返回给前端,这样前端调用北京同域名下的服务就和调用上海的服务效果相同了。

 

JSONP:JSONP可用于解决主流浏览器GET请求的跨域数据访问的问题。

a去声明,b域名去调用。

在www.aaa.com页面中:

<script>

 function jsonp(json){

  alert(json[“name”]);

}

</script>

<script src=http://www.bbb.com/jsonp.js></script>

在www.bbb.com页面中:

  jsonp({‘name’:’ax’,’age’:23});

 

jsonp跨域只对GET请求起作用,对POST请求不行。

前端页面GET请求处有两处改动:dataType:”jsonp”, jsonp:”callback”.后端代码在GET请求处通过名字callback获取jsonp:$jsonp=$_GET[“callback”];

实现代码jsonpdemeo.html:

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

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Demo</title>

<style>

 body,input,button,select,h1{

                                                                    font-size:26px;

                                                                    line-height:1.8;

 }

</style>

</head>

 

<body>

<h1>员工查询</h1>

<label>请输入员工编号</label>

<input type="text" id="keyword" />

<button id="search">查询</button>

<p id="searchResult"></p>

 

<h1>员工创建</h1>

<label>请输入员工姓名:</label>

<input type="text" id="staffName" /><br/>

<label>请输入员工编号:</label>

<input type="text" id="staffNumber" /><br/>

<label>请输入员工性别:

<select id="staffSex">

  <option>男</option>

  <option>女</option>

</select>

</label><br/>

<label>请输入员工职位:</label>

<input type="text" id="staffJob" /><br/>

<button id="save">保存</button>

<p id="createResult"></p>

 

 

<script src="http://www.mamicode.com/jquery-3.1.1.js"></script>

<script>

$(document).ready(function(){

  $("#search").click(function(){

     $.ajax({

                                                                      type:"GET",

                                                                      url:"http://127.0.0.1:8081/ajaxdemo/jsonpservice1.php?number="+$("#keyword").val(),

                                                                      dataType:"jsonp",

                                                                      jsonp:"callback",

                                                                      success:function(data){

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

                                                                                                                                                       $("#searchResult").html(data.msg);

                                                                                     }else{

                                                                                        $("#searchResult").html("出现错误:"+data.msg);                                       

                                                                               }

                                                                            },

                                                                            error:function(jqXHR){

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

                                                                       }

                                                                     

                                                                   });

  });

 

 

 $("#save").click(function(){

     $.ajax({

                                                                      type:"POST",

                                                                      url:"http://127.0.0.1:8081/ajaxdemo/jsonpservice1.php",

                                                                      dataType:"json",

                                                                      data:{

                                                                               name:$("#staffName").val(),

                                                                               number:$("#staffNumber").val(),

                                                                               sex:$("#staffSex").val(),

                                                                               job:$("#staffJob").val()

                                                                            },

                                                                      success:function(data){

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

                                                                                                                                                       $("#createResult").html(data.msg);

                                                                                     }else{

                                                                                        $("#createResult").html("出现错误:"+data.msg);                                       

                                                                               }

                                                                            },

                                                                            error:function(jqXHR){

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

                                                                       }

                                                                     

                                                                   });

  });

 

 });

</script>

</body>

</html>

服务器端代码jsonpservice1.php:

<?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();

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

                                                                   create();

}

 

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

function search(){

                                                                   $jsonp=$_GET["callback"];

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

                                                                   //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 =$jsonp.‘({"success":false,"msg":"没有找到员工。"})‘;

                                                                  

                                                                   //遍历$staff多维数组,查找key值为number的员工是否存在,如果存在,则修改返回结果

                                                                   foreach ($staff as $value) {

                                                                            if ($value["number"] == $number) {

                                                                                    $result =$jsonp.‘({"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"].‘信息保存成功!"}‘;

}

 

 

XHR2:

Html5提供的XMLHttpRequest Level2已经实现了跨域访问及其他的一些新功能;IE10以下不支持XHR2;在服务器端做一些小小的改造即可:

header(‘Access-Control-Allow-Origin:*’);

header(‘Access-Control-Allow-Methods:POST,GET’);

 

实现代码XHR2demo.html:

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

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Demo</title>

<style>

 body,input,button,select,h1{

                                                                    font-size:26px;

                                                                    line-height:1.8;

 }

</style>

</head>

 

<body>

<h1>员工查询</h1>

<label>请输入员工编号</label>

<input type="text" id="keyword" />

<button id="search">查询</button>

<p id="searchResult"></p>

 

<h1>员工创建</h1>

<label>请输入员工姓名:</label>

<input type="text" id="staffName" /><br/>

<label>请输入员工编号:</label>

<input type="text" id="staffNumber" /><br/>

<label>请输入员工性别:

<select id="staffSex">

  <option>男</option>

  <option>女</option>

</select>

</label><br/>

<label>请输入员工职位:</label>

<input type="text" id="staffJob" /><br/>

<button id="save">保存</button>

<p id="createResult"></p>

 

 

<script src="http://www.mamicode.com/jquery-3.1.1.js"></script>

<script>

$(document).ready(function(){

  $("#search").click(function(){

     $.ajax({

                                                                      type:"GET",

                                                                      url:"http://127.0.0.1:8081/ajaxdemo/XHR2service1.php?number="+$("#keyword").val(),

                                                                      dataType:"json",

                                                                      success:function(data){

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

                                                                                                                                                       $("#searchResult").html(data.msg);

                                                                                     }else{

                                                                                        $("#searchResult").html("出现错误:"+data.msg);                                       

                                                                               }

                                                                            },

                                                                            error:function(jqXHR){

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

                                                                       }

                                                                     

                                                                   });

  });

 

 

 $("#save").click(function(){

     $.ajax({

                                                                      type:"POST",

                                                                      url:"http://127.0.0.1:8081/ajaxdemo/XHR2service1.php",

                                                                      dataType:"json",

                                                                      data:{

                                                                               name:$("#staffName").val(),

                                                                               number:$("#staffNumber").val(),

                                                                               sex:$("#staffSex").val(),

                                                                               job:$("#staffJob").val()

                                                                            },

                                                                      success:function(data){

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

                                                                                                                                                       $("#createResult").html(data.msg);

                                                                                     }else{

                                                                                        $("#createResult").html("出现错误:"+data.msg);                                       

                                                                               }

                                                                            },

                                                                            error:function(jqXHR){

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

                                                                       }

                                                                     

                                                                   });

  });

 

 });

</script>

</body>

</html>

服务器端代码XHR2service1.php:

<?php

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

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

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

header("Access-Control-Allow-Origin:*");

header("Access-Control-Allow-Methods:POST,GET");

//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();

} else if ($_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学习笔记4-跨域(大拇指向上)