search
HomeWeb Front-endJS TutorialAjax front-end and back-end cross-domain request processing methods

This article introduces the ajax front-end cross-domain request processing and background cross-domain data processing methods, and analyzes the ajax cross-domain issues in detail. Friends who need to learn about the ajax front-end and back-end cross-domain request processing methods can read this article.

I have been working on the front-end development of public accounts recently, and encountered the problem of ajax cross-domain requests, such as the three-level linkage of province-city-county in the region, the three-level linkage query of car brand-car series-car model, etc. All need to be completed by calling external interfaces (interfaces of other engineering projects). Now I will share my personal solution to cross-domain requests. Of course, with the help of the background programmer, I figured out the origin of it. I quickly recorded it and accumulated it slowly. I hope it can be helpful to everyone. Please also ask. Actively provide comments or suggestions.

Cross-domain requests require the use of background code to receive callbackCallback function to further process the json data; the frontend then uses an ajax request to send callback parameters to the server and specify the data format as jsonp.

1. Processing cross-domain requests in the background

1.CarBrandController.java (car brand interface java file), the methods listed here are mainly used to query the corresponding according to different level values Brand, car series, car model. Here, a callback function is processed for cross-domain requests. If the returned callback is null, it is not a cross-domain request. No special processing is required. Just print the json interface data directly; if If the returned callback is not null, it indicates a cross-domain request. In this case, special processing is required for the json data, that is, a pair of parentheses are added to the outer layer of the json data. For details, please see the printlnJSONObject method in the HttpAdapter.java file. .

public void json(HttpServletRequest request,HttpServletResponse response){ 
  Map<String,Object>map=new HashMap<String, Object>(); 
  String id = request.getParameter("id");      //接收ajax请求带过来的id 
  String level = request.getParameter("level");   //接收ajax请求带过来的level 
  String callback=request.getParameter("callback"); //接收ajax请求带过来的callback参数 
  if ("1".equals(level)) {             //如果level是&#39;1&#39;,则查询第一级目录内容 
    map.put("results", this.carBrandService.findByAttr(null, "first_letter asc")); //调用查询方法,结果放入map 
  } else if ("2".equals(level)) {          //如果level是&#39;2&#39;,则查询第二级目录内容 
    map.put("results", this.carSerieService.findByAttr("parent_id="+id, "first_letter asc"));//调用查询方法,结果放入map 
  } else if ("3".equals(level)) {          //如果level是&#39;3&#39;,则查询第三极目录内容 
    map.put("results", this.carModelYearService.findByAttr("parent_id="+id, "jian_pin desc"));//调用查询方法,结果放入map 
  } 
  map.put("level",level); 
  if (null==callback) {               //如果接收的callback值为null,则是不跨域的请求,输出json对象 
    HttpAdapter.printlnObject(response, map); 
  }else{                      //如果接收的callback值不为null,则是跨域请求,输出跨域的json对象 
  HttpAdapter.printlnJSONPObject(response, map, callback); 
  } 
}

2.HttpAdapter.java (java file of output object), printlnObject method prints normal json string; printlnJSONObject method performs special processing on json string.

/** 
 * 打印对象 
 * @param response 
 * @param object 
*/ 
public static void printlnObject(HttpServletResponse response,Object object){ 
  PrintWriter writer=getWriter(response); 
  writer.println(JSON.toJSONString(object)); 
} 
/** 
 * 打印跨域对象 
 * @param response 
 * @param object 
*/ 
public static void printlnJSONPObject(HttpServletResponse response,Object object,String callback){ 
  PrintWriter writer=getWriter(response); 
  writer.println(callback+"("+JSON.toJSONString(object)+")"); 
}

2. Front-end ajax cross-domain request data

Writing method 1: Send a parameter callback= to the server? , and specify the dataType as 'jsonp' format. The data format specified during cross-domain requests must be in the form of jsonp.

function loadData(obj,level,id,value){ 
  $.ajax({  
    url:&#39;http://192.168.1.106:8086/carBrand/json.html?level=&#39;+level+&#39;&id=&#39;+id+&#39;&callback=?&#39;,   //将callback写在请求url后面作为参数携带 
    type:&#39;GET&#39;, 
    async:false, 
    dataType:&#39;jsonp&#39;, 
    success:function(data){         
      console.log(data);             
      //其他处理(动态添加数据元素)       
  });    
}

Writing method 2: The callback does not need to be written in the url, but the jsonp parameter must be specified as 'callback' and a value should be given to the jsonpCallback parameter.

function loadData(obj,level,id,value){ 
  $.ajax({  
    url:&#39;http://192.168.1.106:8086/carBrand/json.html?level=&#39;+level+&#39;&id=&#39;+id, 
    type:&#39;GET&#39;, 
    dataType:&#39;jsonp&#39;, 
    jsonp: &#39;callback&#39;,          //将callback写在jsonp里作为参数连同请求一起发送 
    jsonpCallback:&#39;jsonpCallback1&#39;,    
    success:function(data){            
    console.log(data);       
}); }

The above two ways of writing have the same meaning, but they are written in different ways.

Next, I will add the working principle of jsonp.

3. Analysis of the cross-domain principle of jsonp

The most basic principle of jsonp is: dynamically add a <script> tag, and the src attribute of the script tag is not cross-domain of restrictions. In this way, this cross-domain method has nothing to do with the ajax XmlHttpRequest protocol. <br/></script>

JSONP is an unofficial protocol that allows Script tags to be integrated on the server side and returned to the client through javascript The callback form implements cross-domain access to JSONP, that is, JSON with Padding. Due to the restrictions of the same-origin policy, XmlHttpRequest is only allowed to request resources from the current source (domain name, protocol, port). If we want to make a cross-domain request, we can make a cross-domain request by using the script tag of html and return the script code to be executed in the response, in which the javascript object can be passed directly using JSON. This cross-domain communication method is called JSONP.

jsonCallback function jsonp1236827957501(....): It is registered by the browser client. After obtaining the json data on the cross-domain server, the callback function

Jsonp principle:

First register a callback (such as: 'jsoncallback') on the client, and then pass the callback name (such as: jsonp1236827957501) to the server. Note: After the server obtains the callback value, it must use jsonp1236827957501(...) to include the json content to be output. At this time, the json data generated by the server can be correctly received by the client.

Then use javascript syntax to generate a function. The function name is the value jsonp1236827957501 of the passed parameter 'jsoncallback'.

Finally, place the json data directly as an input parameter. function, this generates a js syntax document and returns it to the client.

The client browser parses the script tag and executes the returned javascript document. At this time, the javascript document data is passed as a parameter to the callback function predefined by the client (such as jquery in the above example) The $.ajax() method encapsulates the success: function (json)). (Dynamic execution callback function)

It can be said that the jsonp method is in principle the same as are consistent (qq space uses this method to achieve cross-domain data exchange). JSONP is a script injection (Script Injection) behavior, so there are Certain security risks.

Note that jquey does not support post cross-domain.

That’s all the above content. If you are not familiar with ajax cross-domain requests, you can read more. !

Recommended similar articles:

Detailed example of the solution to the ajax cross-domain access error 501

This article mainly introduces in detail the solution to the ajax cross-domain access error 501, which has certain reference Value, interest...

Ajax cross-domain perfect solution example sharing

The company wants to create an event page and discover all the information in the process interface, ajax request cross-domain. Here is a brief introduction to cross-domain...

Solution to the problem of cookie loss in Ajax cross-domain access_AJAX related

This article mainly introduces Ajax cross-domain access cookie loss problem, friends in need can refer to it...

The above is the detailed content of Ajax front-end and back-end cross-domain request processing methods. 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
如何使用CakePHP中的AJAX?如何使用CakePHP中的AJAX?Jun 04, 2023 pm 08:01 PM

作为一种基于MVC模式的PHP框架,CakePHP已成为许多Web开发人员的首选。它的结构简单,易于扩展,而其中的AJAX技术更是让开发变得更加高效。在本文中,将介绍如何使用CakePHP中的AJAX。什么是AJAX?在介绍如何在CakePHP中使用AJAX之前,我们先来了解一下什么是AJAX。AJAX是“异步JavaScript和XML”的缩写,是指一种在

Scrapy基于Ajax异步加载实现方法Scrapy基于Ajax异步加载实现方法Jun 22, 2023 pm 11:09 PM

Scrapy是一个开源的Python爬虫框架,它可以快速高效地从网站上获取数据。然而,很多网站采用了Ajax异步加载技术,使得Scrapy无法直接获取数据。本文将介绍基于Ajax异步加载的Scrapy实现方法。一、Ajax异步加载原理Ajax异步加载:在传统的页面加载方式中,浏览器发送请求到服务器后,必须等待服务器返回响应并将页面全部加载完毕才能进行下一步操

jquery ajax报错403怎么办jquery ajax报错403怎么办Nov 30, 2022 am 10:09 AM

jquery ajax报错403是因为前端和服务器的域名不同而触发了防盗链机制,其解决办法:1、打开相应的代码文件;2、通过“public CorsFilter corsFilter() {...}”方法设置允许的域即可。

Nginx中404页面怎么配置及AJAX请求返回404页面Nginx中404页面怎么配置及AJAX请求返回404页面May 26, 2023 pm 09:47 PM

404页面基础配置404错误是www网站访问容易出现的错误。最常见的出错提示:404notfound。404错误页的设置对网站seo有很大的影响,而设置不当,比如直接转跳主页等,会被搜索引擎降权拔毛。404页面的目的应该是告诉用户:你所请求的页面是不存在的,同时引导用户浏览网站其他页面而不是关掉窗口离去。搜索引擎通过http状态码来识别网页的状态。当搜索引擎获得了一个错误链接时,网站应该返回404状态码,告诉搜索引擎放弃对该链接的索引。而如果返回200或302状态码,搜索引擎就会为该链接建立索引

ajax传递中文乱码怎么办ajax传递中文乱码怎么办Nov 15, 2023 am 10:42 AM

ajax传递中文乱码的解决办法:1、设置统一的编码方式;2、服务器端编码;3、客户端解码;4、设置HTTP响应头;5、使用JSON格式。详细介绍:1、设置统一的编码方式,确保服务器端和客户端使用相同的编码方式,通常情况下,UTF-8是一种常用的编码方式,因为它可以支持多种语言和字符集;2、服务器端编码,在服务器端,确保将中文数据以正确的编码方式进行编码,再传递给客户端等等。

什么是ajax重构什么是ajax重构Jul 01, 2022 pm 05:12 PM

ajax重构指的是在不改变软件现有功能的基础上,通过调整程序代码改善软件的质量、性能,使其程序的设计模式和架构更合理,提高软件的扩展性和维护性;Ajax的实现主要依赖于XMLHttpRequest对象,由于该对象的实例在处理事件完成后就会被销毁,所以在需要调用它的时候就要重新构建。

在Laravel中如何通过Ajax请求传递CSRF令牌?在Laravel中如何通过Ajax请求传递CSRF令牌?Sep 10, 2023 pm 03:09 PM

CSRF代表跨站请求伪造。CSRF是未经授权的用户冒充授权执行的恶意活动。Laravel通过为每个活动用户会话生成csrf令牌来保护此类恶意活动。令牌存储在用户的会话中。如果会话发生变化,它总是会重新生成,因此每个会话都会验证令牌,以确保授权用户正在执行任何任务。以下是访问csrf_token的示例。生成csrf令牌您可以通过两种方式获取令牌。通过使用$request→session()→token()直接使用csrf_token()方法示例<?phpnamespaceApp\Http\C

使用HTML5文件上传与AJAX和jQuery使用HTML5文件上传与AJAX和jQuerySep 13, 2023 am 10:09 AM

当提交表单时,捕获提交过程并尝试运行以下代码片段来上传文件-//File1varmyFile=document.getElementById(&#39;fileBox&#39;).files[0];varreader=newFileReader();reader.readAsText(file,&#39;UTF-8&#39;);reader.onload=myFunc;functionmyFunc(event){&nbsp;&nbsp;varres

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools