Home >Web Front-end >JS Tutorial >Introduction to jsonp cross-domain requests

Introduction to jsonp cross-domain requests

零下一度
零下一度Original
2017-07-16 15:22:241413browse

This article mainly introduces the relevant information of jsonp cross-domain request to everyone in detail, and activates the encapsulation of all interfaces to support browser cross-domain requests, which has certain reference value.

Separate instructions:

1. JSONP:

Intuitive understanding:

is to dynamically register a function on the client

function a(data), and then pass the function name to the server, and the server returns a({/*json*/}) to the client to run, thus calling the client's

function a(data), thus achieving Cross-domain.

Birth background:

1. Ajax directly requests ordinary files, which has the problem of cross-domain access without permission, regardless of whether it is a static page, dynamic web page, web service, wcf, as long as It is a cross-domain request and will not work.

2. However, this is not affected when calling js files on web pages

3. Further promotion, we found that all tags with Src attributes have cross-domain capabilities, such as: <script> To access data, you can only use the following method: try to load the data into js format text on the remote server for client calling and further processing. </script>

5. JSON is a pure character data format and can be natively supported by js.

6. Here is the solution: the web client calls the dynamically generated js format file (usually with json as the suffix) on the cross-domain server in exactly the same way as calling the script.

7. After the client successfully calls the json file, it will get the required data, and the rest is to process it according to its own needs.

8In order to facilitate

clients to use

data, an informal transmission protocol has gradually formed, called jsonp. A key point of this protocol is to allow users to pass a callback parameter to the server, and then when the server returns data, it will use this callback parameter as a function name to wrap the json data, so that the client can customize its own function to process the returned data. Specific implementation:

Whether it is jQuery, extjs, or other frameworks that support jsonp, the work they do behind the scenes is the same. Let me explain it step by step. Implementation of jsonp on the client side:

1. We know that even if the code in the cross-domain js file (which of course complies with the web script security policy), the web page can be executed unconditionally.

There is a remote.js file in the root directory of remote server remoteserver.com with the following code:

alert('I am

remote file

');Not much to say, see the core code

1. Define a class, inherit MappingJackson2HttpMessageConverter, rewrite the writeInternal method, and simply judge whether there is a callback parameter in the method. If there is no direct return of data, if so, the data Wrap the value of the callback parameter in parentheses and return it.

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonProcessingException;

public class CallbackMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

 // 做jsonp的支持的标识,在请求参数中加该参数
 private String callbackName;

 @Override
 protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException,
   HttpMessageNotWritableException {
  // 从threadLocal中获取当前的Request对象
  HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
    .currentRequestAttributes()).getRequest();
  String callbackParam = request.getParameter(callbackName);
  if (StringUtils.isEmpty(callbackParam)) {
   // 没有找到callback参数,直接返回json数据
   super.writeInternal(object, outputMessage);
  } else {
   JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
   try {
    String result = callbackParam + "(" + super.getObjectMapper().writeValueAsString(object)
      + ");";
    IOUtils.write(result, outputMessage.getBody(), encoding.getJavaName());
   } catch (JsonProcessingException ex) {
    throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
   }
  }

 }

 public String getCallbackName() {
  return callbackName;
 }

 public void setCallbackName(String callbackName) {
  this.callbackName = callbackName;
 }

}

2. Define the Java bean, and pay attention to modifying the class scan path, so that the riteInternal method in the MappingJackson2HttpMessageConverter class will be called every time a request comes. If the request comes with a callback parameter, it will be called callbackValue('data ') format data is returned to the front end.

<!-- 定义注解驱动 -->
 <mvc:annotation-driven>
  <mvc:message-converters register-defaults="true">
   <bean
    class="xxx.xxx.xxx.CallbackMappingJackson2HttpMessageConverter">
    <property name="callbackName" value="callback" />
   </bean>
  </mvc:message-converters>
 </mvc:annotation-driven>

3. The front end is called through ajax

encapsulated by

jquery. Some code saving has been made here. The key code has been marked in red

<script type="text/javascript">
 var feedback = {
  init: function(){
   var self = feedback;
   self.bind();
  },
  test: function(data){
   console.log("测试jsonp",data)
  },
  bind: function(){
    var self = feedback;

    var par = {};
     par.callback = &#39;feedback.test&#39;;

    $.ajax({ 
    url:"http://manage.danong.com/rest/open/queryInviteList", 
    data: par,
    dataType:&#39;jsonp&#39;, 
    jsonp:&#39;callback&#39;, 
    timeout:3000 
   }); 
  }
 }
 feedback.init();
</script>
4. The browser prints the log

The above is the detailed content of Introduction to jsonp cross-domain requests. 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