AJAX的跨域问题和同源策略分解了解哪些请求可以跨域------AJAX

134 篇文章 0 订阅
45 篇文章 0 订阅
文章详细讨论了AJAX跨域请求遇到的CORS安全问题,介绍了同源策略如何阻止跨域请求,以及为何浏览器内置的XMLHttpRequest对象导致信息泄露。同时提到了Servlet处理GET和POST请求的示例。
摘要由CSDN通过智能技术生成
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="http://localhost:8081/Test/1.js"></script>
</head>
<body>
<!--    超链接可以跨域-->
    <a href="http://localhost:8081/Test/Test.html">走,跨个域</a>
<!--form表单测试-->
<form action="http://localhost:8081/Test/reg" method="post">
    用户名:<input type="text" name="username">
    密码:<input type="password" name="password">
    <input type="submit" value="注册">
</form>
<script type="text/javascript" src="JS/jQuery-1.0.0.js">
</script>
<script type="text/javascript">
    $(function(){
       $("#AjaxTrans").click(function(){
           let ajax = new XMLHttpRequest();
           ajax.onreadystatechange = function()
           {
               // 默认情况下,ajax发出跨域请求会有以下错误
//1.html:1  Access to XMLHttpRequest at 'http://localhost:8081/Test/hello'
//from origin 'http://localhost:8080' has been blocked by CORS policy:
//No 'Access-Control-Allow-Origin' header is present on the requested resource.
               //CORS策略阻止,这个ajax请求被同源策略阻止了
               //两个站点共享了xmlHttpRequest对象
               //因为页面的XmlHttpRequest对象不可以共享,一旦共享,对方就可以拿到我们的responseHtml
               //同源策略是浏览器的安全策略
               //协议,端口号,域名一致才是同源
               //同源才可以共享,不同源任何信息都不能共享
               //在我们此前所有的跳转和发送请求中,本质都是通过浏览器地址栏跳转来实现的,他们都没有安全问题
               //为什么ajax不行,因为只有它发送请求依靠的是我们浏览器内置的XmlHttpRequest对象
               //当我们A发送AJAX请求到B站点的时候,相当于我们两个站点共享了XmlHttpRequest对象
               //两个站点就都可以获取彼此的response信息,用户的宝贵信息就泄露了
               if (ajax.readyState === 4) {
                   if (ajax.status === 200) {
                       $("#myDiv").html(ajax.responseText);
                   }
                   else
                   {
                       alert(ajax.status);
                   }
               }
           }
           ajax.open("GET","http://localhost:8081/Test/hello",true);
           ajax.send();
       });
    });
</script>
<button onclick="window.location.href='http://localhost:8081/Test/Test.html'">跳页面</button>
<button id="AjaxTrans">ajax跨域请求</button>
<div id="MyDiv"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="http://localhost:8081/Test/1.js"></script>
</head>
<body>
<!--    超链接可以跨域-->
    <a href="http://localhost:8081/Test/Test.html">走,跨个域</a>
<!--form表单测试-->
<form action="http://localhost:8081/Test/reg" method="post">
    用户名:<input type="text" name="username">
    密码:<input type="password" name="password">
    <input type="submit" value="注册">
</form>
<script type="text/javascript" src="JS/jQuery-1.0.0.js">
</script>
<script type="text/javascript">
    $(function(){
       $("#AjaxTrans").click(function(){
           let ajax = new XMLHttpRequest();
           ajax.onreadystatechange = function()
           {
               // 默认情况下,ajax发出跨域请求会有以下错误
//1.html:1  Access to XMLHttpRequest at 'http://localhost:8081/Test/hello'
//from origin 'http://localhost:8080' has been blocked by CORS policy:
//No 'Access-Control-Allow-Origin' header is present on the requested resource.
               //CORS策略阻止,这个ajax请求被同源策略阻止了
               //两个站点共享了xmlHttpRequest对象
               //因为页面的XmlHttpRequest对象不可以共享,一旦共享,对方就可以拿到我们的responseHtml
               //同源策略是浏览器的安全策略
               //协议,端口号,域名一致才是同源
               //同源才可以共享,不同源任何信息都不能共享
               //在我们此前所有的跳转和发送请求中,本质都是通过浏览器地址栏跳转来实现的,他们都没有安全问题
               //为什么ajax不行,因为只有它发送请求依靠的是我们浏览器内置的XmlHttpRequest对象
               //当我们A发送AJAX请求到B站点的时候,相当于我们两个站点共享了XmlHttpRequest对象
               //两个站点就都可以获取彼此的response信息,用户的宝贵信息就泄露了
               if (ajax.readyState === 4) {
                   if (ajax.status === 200) {
                       $("#myDiv").html(ajax.responseText);
                   }
                   else
                   {
                       alert(ajax.status);
                   }
               }
           }
           ajax.open("GET","http://localhost:8081/Test/hello",true);
           ajax.send();
       });
    });
</script>
<button οnclick="window.location.href='http://localhost:8081/Test/Test.html'">跳页面</button>
<button id="AjaxTrans">ajax跨域请求</button>
<div id="MyDiv"></div>
</body>
</html>
// 封装一个函数,通过这个函数就可以获取页面中的元素了
function JQuery(selector)//可能时#id或者.class这样的类选择器
{
    if(typeof selector === "string")
    {
        // 设计思路根据CSS语法
        if (selector.charAt(0) === "#")
        {
            // 根据ID获取元素
            //这个是全局对象,是根据我们的ID获取的dom对象
            IE = document.getElementById(selector.substring(1));
            //返回JQuery对象,这个有html方法
            return new JQuery();
        }
    }
    if(typeof selector === "function")
    {
        window.onload = selector;
    }
    //定义一个HTML方法
    this.html = function(htmlStr)
    {
        IE.innerHTML = htmlStr;
    }
    //定义一个click函数代替onclick方法
    this.click = function(fun)
    {
        IE.onclick = fun;
    }
    //下拉栏变化
    this.change = function(fun)
    {
        IE.onchange = fun;
    }
    //由此可知
    this.val = function(value)
    {
        if(value === undefined)
        {
            return IE.value;
        }
        else
        {
            IE.value = value;
        }
    }
    //定义一个静态方法用来发送AJAX请求
    //JS中的静态方法也还是需要有这个对象的
    //传递参数如下,1.传递的数据2.请求方法3.url地址4.是否异步执行
    JQuery.ajax = function(JsonArgs)
    {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function()
        {
            if (this.readyState === 4)
            {
                if (this.status === 200)
                {
                    var JsonObj = JSON.parse(this.responseText);
                    JsonArgs.success(JsonObj);
                }
                else
                {
                    alert(this.status);
                }
            }
        }
        if(JsonArgs.type.toUpperCase() === "POST")
        {
            xhr.open("POST",JsonArgs.url,JsonArgs.async);
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xhr.send(JsonArgs.data);
        }
        if(JsonArgs.type.toUpperCase() === "GET")
        {
            JsonArgs.type = "GET";
            xhr.open("GET",JsonArgs.url+"?"+JsonArgs.data,JsonArgs.async);
            xhr.send();
        }
    }
}
$ = JQuery;
//执行这个的目的是为了让静态方法能生效
new JQuery();
// 封装一个函数,通过这个函数就可以获取页面中的元素了
function JQuery(selector)//可能时#id或者.class这样的类选择器
{
    if(typeof selector === "string")
    {
        // 设计思路根据CSS语法
        if (selector.charAt(0) === "#")
        {
            // 根据ID获取元素
            //这个是全局对象,是根据我们的ID获取的dom对象
            IE = document.getElementById(selector.substring(1));
            //返回JQuery对象,这个有html方法
            return new JQuery();
        }
    }
    if(typeof selector === "function")
    {
        window.onload = selector;
    }
    //定义一个HTML方法
    this.html = function(htmlStr)
    {
        IE.innerHTML = htmlStr;
    }
    //定义一个click函数代替onclick方法
    this.click = function(fun)
    {
        IE.onclick = fun;
    }
    //下拉栏变化
    this.change = function(fun)
    {
        IE.onchange = fun;
    }
    //由此可知
    this.val = function(value)
    {
        if(value === undefined)
        {
            return IE.value;
        }
        else
        {
            IE.value = value;
        }
    }
    //定义一个静态方法用来发送AJAX请求
    //JS中的静态方法也还是需要有这个对象的
    //传递参数如下,1.传递的数据2.请求方法3.url地址4.是否异步执行
    JQuery.ajax = function(JsonArgs)
    {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function()
        {
            if (this.readyState === 4)
            {
                if (this.status === 200)
                {
                    var JsonObj = JSON.parse(this.responseText);
                    JsonArgs.success(JsonObj);
                }
                else
                {
                    alert(this.status);
                }
            }
        }
        if(JsonArgs.type.toUpperCase() === "POST")
        {
            xhr.open("POST",JsonArgs.url,JsonArgs.async);
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xhr.send(JsonArgs.data);
        }
        if(JsonArgs.type.toUpperCase() === "GET")
        {
            JsonArgs.type = "GET";
            xhr.open("GET",JsonArgs.url+"?"+JsonArgs.data,JsonArgs.async);
            xhr.send();
        }
    }
}
$ = JQuery;
//执行这个的目的是为了让静态方法能生效
new JQuery();
alert("我是B应用的文件");
alert("我是B应用的文件");
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/hello")
public class Hello extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println("Halla Ajax");
    }
}
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/hello")
public class Hello extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println("Halla Ajax");
    }
}
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/reg")
public class Test extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        PrintWriter out = response.getWriter();
        out.println(username+password);
    }
}
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/reg")
public class Test extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        PrintWriter out = response.getWriter();
        out.println(username+password);
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>欢迎来到测试应用</h1>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>欢迎来到测试应用</h1>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值