


Ajax front-end and back-end cross-domain request processing methods (graphic tutorial)
This article introduces the front-end cross-domain request processing and the back-end cross-domain data processing methods, and analyzes the cross-domain issues of ajax in detail. Friends who need this can learn from it.
Cross-domain requests need to use the background code to receive the callback function and further process the json data; the frontend then uses an ajax request to send the 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是'1',则查询第一级目录内容 map.put("results", this.carBrandService.findByAttr(null, "first_letter asc")); //调用查询方法,结果放入map } else if ("2".equals(level)) { //如果level是'2',则查询第二级目录内容 map.put("results", this.carSerieService.findByAttr("parent_id="+id, "first_letter asc"));//调用查询方法,结果放入map } else if ("3".equals(level)) { //如果level是'3',则查询第三极目录内容 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 (output object's java file), the printlnObject method prints a normal json string; the printlnJSONObject method performs special processing on the 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:'http://192.168.1.106:8086/carBrand/json.html?level='+level+'&id='+id+'&callback=?', //将callback写在请求url后面作为参数携带 type:'GET', async:false, dataType:'jsonp', 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:'http://192.168.1.106:8086/carBrand/json.html?level='+level+'&id='+id, type:'GET', dataType:'jsonp', jsonp: 'callback', //将callback写在jsonp里作为参数连同请求一起发送 jsonpCallback:'jsonpCallback1', success:function(data){ console.log(data); }); }
The above two ways of writing have the same meaning, but they are written in different ways.
Next, 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 has no cross-domain restrictions. . In this way, this cross-domain method has nothing to do with the ajax XmlHttpRequest protocol. </p> <p>JSONP is an unofficial protocol that allows the integration of Script tags on the server side and returns it to the client, implemented in the form of javascript callback Cross-domain access to JSONP 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, where the javascript object can be passed directly using JSON. This cross-domain communication method is called JSONP. </p> <p>jsonCallback function jsonp1236827957501(....): It is registered by the browser client. After obtaining the json data on the cross-domain server, the callback function </p> <p><strong>Jsonp principle:</strong></p> <p>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 gets 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. </p> <p>Then use javascript syntax to generate a function. The function name is the value jsonp1236827957501 of the passed parameter 'jsoncallback'.</p> <p>Finally, place the json data directly as an input parameter. function, this generates a js syntax document and returns it to the client. </p> <p>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) In the success: function (json)) encapsulated by the $.ajax() method. (Dynamic execution of the callback function) <br></p> It can be said that the jsonp method is in principle the same as <script src="http://cross-domain /...xx.js"></script> 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.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future. Related articles:Detailed explanation of the working principle of AJAX and its advantages and disadvantages
How to implement the non-refresh paging function with PHP Ajax
php ajaxMethod of asynchronously uploading files or images
The above is the detailed content of Ajax front-end and back-end cross-domain request processing methods (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

1. First, we right-click the blank space of the taskbar and select the [Task Manager] option, or right-click the start logo, and then select the [Task Manager] option. 2. In the opened Task Manager interface, we click the [Services] tab on the far right. 3. In the opened [Service] tab, click the [Open Service] option below. 4. In the [Services] window that opens, right-click the [InternetConnectionSharing(ICS)] service, and then select the [Properties] option. 5. In the properties window that opens, change [Open with] to [Disabled], click [Apply] and then click [OK]. 6. Click the start logo, then click the shutdown button, select [Restart], and complete the computer restart.

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

In the process of PHP development, dealing with special characters is a common problem, especially in string processing, special characters are often escaped. Among them, converting special characters into single quotes is a relatively common requirement, because in PHP, single quotes are a common way to wrap strings. In this article, we will explain how to handle special character conversion single quotes in PHP and provide specific code examples. In PHP, special characters include but are not limited to single quotes ('), double quotes ("), backslash (), etc. In strings

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.
