Home  >  Article  >  Java  >  Let’s take a look at Java Ajax jsonp cross-domain requests

Let’s take a look at Java Ajax jsonp cross-domain requests

coldplay.xixi
coldplay.xixiforward
2020-08-25 17:15:191968browse

Let’s take a look at Java Ajax jsonp cross-domain requests

[Related learning recommendations: java basic tutorial]

1. What is JSONP

Generally speaking, the web page located at server1.example.com cannot communicate with a server other than server1.example.com. The exception is the HTML 3f1c4e4b6b16bbbd69b2ee476dc4f83a element. Using this open policy of the 3f1c4e4b6b16bbbd69b2ee476dc4f83a element, web pages can obtain JSON data dynamically generated from other sources, and this usage pattern is called JSONP. The data captured with JSONP is not JSON, but arbitrary JavaScript, which is executed with a JavaScript interpreter instead of parsed with a JSON parser.

JSONP is a protocol designed to solve the problem of cross-domain requests from clients to servers, but it is not a formal transmission protocol. A key point of this protocol is to allow users to pass a callback parameter to the server. Then when the server returns data, it will use this callback parameter as a function name to wrap the JSON data. In this way, the client can customize its own function to automatically process the return. The data.

2. Ajax requests other domain interfaces

My project needs to request another first background interface to request data, which is rendered on the page. When loading data through ajax as follows:

  $.ajax({
        url: 'http://www.xxx.cn/lalala?method=10082&page=1&pageSize=10',
        type: 'GET',
        dataType: 'json',
        timeout: 5000,
        contentType: 'application/json; charset=utf-8',
        success: function (result) {
          alter("aaaa");
        }
      });

In this way, a cross-domain error occurs, as shown below:

No 'Access-Control-Allow-Origin' header is present on the requested resource . Origin 'null' is therefore not allowed access. The response had HTTP status code 500.

This means that cross-domain requests are not allowed, so what should I do? Just change it to jsonp. Just change the dataType field.

  $.ajax({
        url: 'http://www.xxx.cn/lalala?method=10082&page=1&pageSize=10',
        type: 'GET',
        dataType: 'jsonp',
        timeout: 5000,
        contentType: 'application/json; charset=utf-8',
        success: function (result) {
          alter("aaaa");
        }
      });

Result: Uncaught SyntaxError: Unexpected token!

what the fuck! Obviously requesting data back, the result is still an error. The reason is that ajax requests the server, and the returned data format does not conform to the return format of jsonp. So what is the jsonp format?

Callback({msg:'this is json data'})

What kind of thing is this? Who defines it as weird! If you think so, it seems that you have not looked at point 1 carefully. JSON is a lightweight data exchange format, like xml. JSONP is a way of using JSON data. What is returned is not a JSON object, but a javaScript script containing a JSON object. But the picture above is a json string, so an error is reported.

3. Parameter return processing

One thing you will find is that when you request using the jsonp protocol, in addition to the parameters you fill in, there are also There is a parameter named callback, as shown in the figure:

Look at what this parameter is, because I did not specify the jsonp parameter when making the ajax request, then The system default parameter name is "callback". If the jsonpCallback parameter is not specified, jquery will generate a random function name, as shown in the figure above.

For example, if I configure it as follows:

$.ajax({
      url: 'http://www.xxx.cn/lalala?method=10082&page=1&pageSize=10',
      type: 'GET',
      dataType: 'jsonp',
      jsonp:'callbacka',//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)
      jsonpCallback:"success_jsonpCallback",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名
      timeout: 5000,
      contentType: 'application/json; charset=utf-8',
      success: function (result) {
        alter("aaaa");
      }
    });

Then the server can also obtain the callback function name through the following method:

The code is as follows:

string callbackFunName =request.getParameter("callbacka");//获取的就是success_jsonpCallback 字符串

Note: The system is case-sensitive in function names.

Then let’s package it according to the format:

String callback = request.getParameter("callback"); //不指定函数名默认 callback

return callback+ "(" + jsonStr + ")"

After packaging it, the result is really no error. Take a look at the returned data as shown below:

4. JSONP execution process

First register a callback on the client (such as: 'jsoncallback'), 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.

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

Finally, use the json data directly as a parameter. Place it in the function, thus generating a js syntax document and returning 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 the one encapsulated by the jquery $.ajax() method in the above example. success: function (json)).

Recommended related articles: ajax video tutorial

The above is the detailed content of Let’s take a look at Java Ajax jsonp cross-domain requests. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete