search
HomeWeb Front-endJS TutorialHow to use JS and ajax same origin strategy in projects

This time I will show you how to use the JS and ajax homology strategy in the project. What are the precautions for using the JS and ajax homology strategy in the project. The following is a practical case. , let’s take a look.

1. Review of ajax implemented by jQuery

First, let’s talk about the advantages and disadvantages of ajax

advantage:

AJAXUse Javascript technology to send asynchronous requests to the server;

AJAX does not require refreshing the entire page;

Because the server response content is no longer the entire page, but a part of the page, AJAX performance is high;

Ajax implemented by jquery

index.html

nbsp;html>


 <meta>
 <title>Title</title>
 <script></script>


<button>send_Ajax</button>
<script>
 //$.ajax的两种使用方式:
 //$.ajax(settings);
 //$.ajax(url,[settings]);
 $(".send_Ajax").click(function(){
  $.ajax({
  url:"/handle_Ajax/",
  type:"POST",
  data:{username:"Yuan",password:123},
  success:function(data){
   alert(data)
  },
   //=================== error============
  error: function (jqXHR, textStatus, err) {
   // jqXHR: jQuery增强的xhr
   // textStatus: 请求完成状态
   // err: 底层通过throw抛出的异常对象,值与错误类型有关
   console.log(arguments);
   },
   //=================== complete============
  complete: function (jqXHR, textStatus) {
   // jqXHR: jQuery增强的xhr
   // textStatus: 请求完成状态 success | error
   console.log(&#39;statusCode: %d, statusText: %s&#39;, jqXHR.status, jqXHR.statusText);
   console.log(&#39;textStatus: %s&#39;, textStatus);
  },
  //=================== statusCode============
  statusCode: {
   &#39;403&#39;: function (jqXHR, textStatus, err) {
   console.log(arguments); //注意:后端模拟errror方式:HttpResponse.status_code=500
   },
   &#39;400&#39;: function () {
   }
  }
  })
 })
</script>

Views.py

import json,time
 
def index(request):
 
 return render(request,"index.html")
 
def handle_Ajax(request):
 
 username=request.POST.get("username")
 password=request.POST.get("password")
 
 print(username,password)
 time.sleep(10)
 
 return HttpResponse(json.dumps("Error Data!"))

$.ajax parameters

Request parameters

######################------------data---------################
  data: 当前ajax请求要携带的数据,是一个json的object对象,ajax方法就会默认地把它编码成某种格式
    (urlencoded:?a=1&b=2)发送给服务端;此外,ajax默认以get方式发送请求。
    function testData() {
    $.ajax("/test",{  //此时的data是一个json形式的对象
     data:{
     a:1,
     b:2
     }
    });     //?a=1&b=2
######################------------processData---------################
processData:声明当前的data数据是否进行转码或预处理,默认为true,即预处理;if为false,
    那么对data:{a:1,b:2}会调用json对象的toString()方法,即{a:1,b:2}.toString()
    ,最后得到一个[object,Object]形式的结果。
   
######################------------contentType---------################
contentType:默认值: "application/x-www-form-urlencoded"。发送信息至服务器时内容编码类型。
    用来指明当前请求的数据编码格式;urlencoded:?a=1&b=2;如果想以其他方式提交数据,
    比如contentType:"application/json",即向服务器发送一个json字符串:
    $.ajax("/ajax_get",{
    
     data:JSON.stringify({
      a:22,
      b:33
     }),
     contentType:"application/json",
     type:"POST",
    
    });       //{a: 22, b: 33}
    注意:contentType:"application/json"一旦设定,data必须是json字符串,不能是json对象
    views.py: json.loads(request.body.decode("utf8"))
######################------------traditional---------################
traditional:一般是我们的data数据有数组时会用到 :data:{a:22,b:33,c:["x","y"]},
    traditional为false会对数据进行深层次迭代;

Response parameters

/*
dataType: 预期服务器返回的数据类型,服务器端返回的数据会根据这个值解析后,传递给回调函数。
   默认不需要显性指定这个属性,ajax会根据服务器返回的content Type来进行转换;
   比如我们的服务器响应的content Type为json格式,这时ajax方法就会对响应的内容
   进行一个json格式的转换,if转换成功,我们在success的回调函数里就会得到一个json格式
   的对象;转换失败就会触发error这个回调函数。如果我们明确地指定目标类型,就可以使用
   data Type。
   dataType的可用值:html|xml|json|text|script
   见下dataType实例
*/

Small exercise: Calculate the sum of two numbers

Method 1: ContentType is not specified here: the default is urlencode.

index.html

nbsp;html>


 <meta>
 <meta>
 <meta>
 <title>Title</title>
 <script></script>
 <script></script>


<h1 id="计算两个数的和-测试ajax">计算两个数的和,测试ajax</h1>
<input>+<input>=<input>
<button>sendajax</button>
<script>
 $(".send_ajax").click(function () {
   $.ajax({
   url:"/sendAjax/",
   type:"post",
   headers:{"X-CSRFToken":$.cookie(&#39;csrftoken&#39;)}, 
   data:{
    num1:$(".num1").val(),
    num2:$(".num2").val(),
   },
   success:function (data) {
    alert(data);
    $(".ret").val(data)
   }
  })
 })
</script>

views.py

def index(request):
 return render(request,"index.html")
def sendAjax(request):
 print(request.POST)
 print(request.GET)
 print(request.body) 
 num1 = request.POST.get("num1")
 num2 = request.POST.get("num2")
 ret = float(num1)+float(num2)
 return HttpResponse(ret)

Method 2: Specify conentType as json data to send:

index2.html

<script>
 $(".send_ajax").click(function () {
   $.ajax({
   url:"/sendAjax/",
   type:"post",
   headers:{"X-CSRFToken":$.cookie(&#39;csrftoken&#39;)}, //如果是json发送的时候要用headers方式解决forbidden的问题
   data:JSON.stringify({
    num1:$(".num1").val(),
    num2:$(".num2").val()
   }),
   contentType:"application/json", //客户端告诉浏览器是以json的格式发的数据,所以的吧发送的数据转成json字符串的形式发送
   success:function (data) {
    alert(data);
    $(".ret").val(data)
   }
  })
 })
</script>

views.py

def sendAjax(request):
 import json
 print(request.POST) #<querydict:>
 print(request.GET) #<querydict:>
 print(request.body) #b'{"num1":"2","num2":"2"}' 注意这时的数据不再POST和GET里,而在body中
 print(type(request.body.decode("utf8"))) # <class>
 # 所以取值的时候得去body中取值,首先得反序列化一下
 data = request.body.decode("utf8")
 data = json.loads(data)
 num1= data.get("num1")
 num2 =data.get("num2")
 ret = float(num1)+float(num2)
 return HttpResponse(ret)</class></querydict:></querydict:>

2. Ajax implemented by JS

1. AJAX core (XMLHttpRequest)

In fact, AJAX adds an additional object to Javascript: the XMLHttpRequest object. All asynchronous interactions are done using the XMLHttpServlet object. In other words, we only need to learn a new object of Javascript.

var xmlHttp = new XMLHttpRequest(); (Most browsers support the DOM2 specification)

Note that each browser has different support for XMLHttpRequest! In order to deal with browser compatibility issues, the following method is given to create an XMLHttpRequest object:

function createXMLHttpRequest() {
    var xmlHttp;
    // 适用于大多数浏览器,以及IE7和IE更高版本
    try{
      xmlHttp = new XMLHttpRequest();
    } catch (e) {
      // 适用于IE6
      try {
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        // 适用于IE5.5,以及IE更早版本
        try{
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){}
      }
    }      
    return xmlHttp;
  }

2. Usage process

1. Open the connection to the server (open)

After getting the XMLHttpRequest object, you can call the open() method of the object to open the connection with the server. The parameters of the open() method are as follows:

open(method, url, async):

method: request method, usually GET or POST;

url: The requested server address, for example: /ajaxdemo1/AServlet. If it is a GET request, you can also add parameters after the URL;

async: This parameter can be omitted, the default value is true, indicating an asynchronous request;

var xmlHttp = createXMLHttpRequest();

xmlHttp.open("GET", "/ajax_get/?a=1", true); 

2. Send request

After using open to open the connection, you can call the send() method of the XMLHttpRequest object to send the request. The parameters of the send() method are POST request parameters, which correspond to the request body content of the HTTP protocol. If it is a GET request, the parameters need to be connected after the URL.

Note: If there are no parameters, null needs to be given as the parameter! If null is not given as a parameter, the FireFox browser may not be able to send requests normally!

xmlHttp.send(null);

3. Receive server response (5 states, 4 processes)

When the request is sent, the server side starts execution, but the server side response has not been received yet. Next we receive the response from the server.

The XMLHttpRequest object has an onreadystatechange event, which is called when the state of the XMLHttpRequest object changes. The following introduces the five states of the XMLHttpRequest object:

0:初始化未完成状态,只是创建了XMLHttpRequest对象,还未调用open()方法;
1:请求已开始,open()方法已调用,但还没调用send()方法;
2:请求发送完成状态,send()方法已调用;
3:开始读取服务器响应;
4:读取服务器响应结束。

onreadystatechange事件会在状态为1、2、3、4时引发。

下面代码会被执行四次!对应XMLHttpRequest的四种状态!

xmlHttp.onreadystatechange = function() {
      alert('hello');
    };

但通常我们只关心最后一种状态,即读取服务器响应结束时,客户端才会做出改变。我们可以通过XMLHttpRequest对象的readyState属性来得到XMLHttpRequest对象的状态。

xmlHttp.onreadystatechange = function() {
      if(xmlHttp.readyState == 4) {
        alert('hello');  
      }
    };

其实我们还要关心服务器响应的状态码xmlHttp.status是否为200,其服务器响应为404,或500,那么就表示请求失败了。我们可以通过XMLHttpRequest对象的status属性得到服务器的状态码。

最后,我们还需要获取到服务器响应的内容,可以通过XMLHttpRequest对象的responseText得到服务器响应内容。

xmlHttp.onreadystatechange = function() {
      if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        alert(xmlHttp.responseText);  
      }
    };

需要注意的:

如果是post请求:

基于JS的ajax没有Content-Type这个参数了,也就不会默认是urlencode这种形式了,需要我们自己去设置
需要设置请求头:xmlHttp.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);
注意 :form表单会默认这个键值对不设定,Web服务器会忽略请求体的内容。
在发送时可以指定请求体了:xmlHttp.send(“username=yuan&password=123”)
基于jQuery的ajax和form发送的请求,都会默认有Content-Type,默认urlencode,
Content-Type:客户端告诉服务端我这次发送的数据是什么形式的
dataType:客户端期望服务端给我返回我设定的格式

如果是get请求:

 xmlhttp.open("get","/sendAjax/?a=1&b=2");

小练习:和上面的练习一样,只是换了一种方式(可以和jQuery的对比一下)

<script>
方式一=======================================
  //基于JS实现实现用urlencode的方式
  var ele_btn = document.getElementsByClassName("send_ajax")[0];
  ele_btn.onclick = function () { //绑定事件
    alert(5555);
    //发送ajax:有一下几步
    //(1)获取XMLResquest对象
    xmlhttp = new XMLHttpRequest();
    //(2)连接服务器
    //get请求的时候,必用send发数据,直接在请求路径里面发
{#    xmlhttp.open("get","/sendAjax/?a=1&b=2");//open里面的参数,请求方式,请求路径#}
    //post请求的时候,需要用send发送数据
    xmlhttp.open("post","/sendAjax/");
    //设置请求头的Content-Type
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //(3)发送数据
    var ele_num1 = document.getElementsByClassName("num1")[0];
    var ele_num2 = document.getElementsByClassName("num2")[0];
    var ele_ret = document.getElementsByClassName("ret")[0];
    var ele_scrf = document.getElementsByName("csrfmiddlewaretoken")[0];
    var s1 = "num1="+ele_num1.value;
    var s2 = "num2="+ele_num2.value;
    var s3 = "&csrfmiddlewaretoken="+ele_scrf.value;
    xmlhttp.send(s1+"&"+s2+s3); //请求数据
    //(4)回调函数,success
    xmlhttp.onreadystatechange = function () {
      if (this.readyState==4&&this.status==200){
        alert(this.responseText);
        ele_ret.value = this.responseText
      }
    }
  }
方式二====================================================
{#  ===================json=============#}
  var ele_btn=document.getElementsByClassName("send_ajax")[0];
  ele_btn.onclick=function () {
    // 发送ajax
     // (1) 获取 XMLHttpRequest对象
     xmlHttp = new XMLHttpRequest();
     // (2) 连接服务器
    // get
    //xmlHttp.open("get","/sendAjax/?a=1&b=2");
    // post
    xmlHttp.open("post","/sendAjax/");
    // 设置请求头的Content-Type
    var ele_csrf=document.getElementsByName("csrfmiddlewaretoken")[0];
    xmlHttp.setRequestHeader("Content-Type","application/json");
    xmlHttp.setRequestHeader("X-CSRFToken",ele_csrf.value); //利用js的方式避免forbidden的解决办法
    // (3) 发送数据
     var ele_num1 = document.getElementsByClassName("num1")[0];
    var ele_num2 = document.getElementsByClassName("num2")[0];
    var ele_ret = document.getElementsByClassName("ret")[0];
    var s1 = ele_num1.value;
    var s2 = ele_num2.value;
    xmlHttp.send(JSON.stringify(
      {"num1":s1,"num2":s2}
    )) ;  // 请求体数据
    // (4) 回调函数 success
    xmlHttp.onreadystatechange = function() {
      if(this.readyState==4 && this.status==200){
        console.log(this.responseText);
        ele_ret.value = this.responseText
      }
    };
  }
</script>

views.py

def sendAjax(request):
  num1=request.POST.get("num1")
  num2 = request.POST.get("num2")
  ret = float(num1)+float(num2)
  return HttpResponse(ret)

JS实现ajax小结

创建XMLHttpRequest对象;
  调用open()方法打开与服务器的连接;
  调用send()方法发送请求;
  为XMLHttpRequest对象指定onreadystatechange事件函数,这个函数会在
  XMLHttpRequest的1、2、3、4,四种状态时被调用;
  XMLHttpRequest对象的5种状态,通常我们只关心4状态。
  XMLHttpRequest对象的status属性表示服务器状态码,它只有在readyState为4时才能获取到。
  XMLHttpRequest对象的responseText属性表示服务器响应内容,它只有在
  readyState为4时才能获取到!

总结:

- 如果"Content-Type"="application/json",发送的数据是对象形式的{},需要在body里面取数据,然后反序列化
= 如果"Content-Type"="application/x-www-form-urlencoded",发送的是/index/?name=haiyan&agee=20这样的数据,
 如果是POST请求需要在POST里取数据,如果是GET,在GET里面取数据

实例(用户名是否已被注册)

7.1 功能介绍

在注册表单中,当用户填写了用户名后,把光标移开后,会自动向服务器发送异步请求。服务器返回true或false,返回true表示这个用户名已经被注册过,返回false表示没有注册过。

客户端得到服务器返回的结果后,确定是否在用户名文本框后显示“用户名已被注册”的错误信息!

7.2 案例分析

页面中给出注册表单;

在username表单字段中添加onblur事件,调用send()方法;

send()方法获取username表单字段的内容,向服务器发送异步请求,参数为username;

django 的视图函数:获取username参数,判断是否为“yuan”,如果是响应true,否则响应false

参考代码:

<script>
    function createXMLHttpRequest() {
      try {
        return new XMLHttpRequest();
      } catch (e) {
        try {
          return new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
          return new ActiveXObject("Microsoft.XMLHTTP");
        }
      }
    }
    function send() {
      var xmlHttp = createXMLHttpRequest();
      xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
          if(xmlHttp.responseText == "true") {
            document.getElementById("error").innerText = "用户名已被注册!";
            document.getElementById("error").textContent = "用户名已被注册!";
          } else {
            document.getElementById("error").innerText = "";
            document.getElementById("error").textContent = "";
          }
        }
      };
      xmlHttp.open("POST", "/ajax_check/", true, "json");
      xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      var username = document.getElementById("username").value;
      xmlHttp.send("username=" + username);
    }
</script>
//--------------------------------------------------index.html
<h1 id="注册">注册</h1>
用户名:
密 码:
//--------------------------------------------------views.py from django.views.decorators.csrf import csrf_exempt def login(request):   print('hello ajax')   return render(request,'index.html')   # return HttpResponse('helloyuanhao') @csrf_exempt def ajax_check(request):   print('ok')   username=request.POST.get('username',None)   if username=='yuan':     return HttpResponse('true')   return HttpResponse('false')

三、同源策略与jsonp

同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。

同源策略,它是由Netscape提出的一个著名的安全策略。现在所有支持JavaScript 的浏览器都会使用这个策略。所谓同源是指,域名,协议,端口相同。当一个浏览器的两个tab页中分别打开来 百度和谷歌的页面当浏览器的百度tab页执行一个脚本的时候会检查这个脚本是属于哪个页面的,即检查是否同源,只有和百度同源的脚本才会被执行。如果非同源,那么在请求数据时,浏览器会在控制台中报一个异常,提示拒绝访问。
jsonp(jsonpadding)

之前发ajax的时候都是在自己给自己的当前的项目下发

现在我们来实现跨域发。给别人的项目发数据,

创建两个项目,先来测试一下

项目一:

<h1 id="项目一">项目一</h1>
<button>jsonp</button>
<script>
  $(".send_jsonp").click(function () {
    $.ajax({
      url:"http://127.0.0.1:8080/ajax_send2/",  #去请求项目二中的url
      success:function (data) {
        console.log(data)
      }
    })
  })
</script>

项目二:

=========================index.html===============
<h1 id="项目二">项目二</h1>
<button>jsonp</button>
<script>
  $(".send_jsonp").click(function () {
    $.ajax({
      url:"/ajax_send2/",
      success:function (data) {
        console.log(data)
      }
    })
  })
</script>

The above is the detailed content of How to use JS and ajax same origin strategy in projects. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send notifications before a task starts in Quartz?How to send notifications before a task starts in Quartz?Apr 04, 2025 pm 09:24 PM

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)