Cross-Origin operations are inevitable when some in-depth front-end programming is performed. JSONP cross-origin GET requests are a common solution, next, let's take a look at how JSONP cross-origin is implemented and discuss the principles of JSONP cross-origin.
1. what is a cross-origin request:
A page on server A requests A handler on server B, which is called A cross-origin request.
The test page is:
The handler kimhandler. ashx is as follows:
% @ WebHandler Language = "C #" Class = "KimHandler" %> using System; using System. web; public class KimHandler: IHttpHandler {public void ProcessRequest (HttpContext context) {string msg = "{\" name \ ": \" kim \ ", \" gender \": \ "male \", \ "age \": 24} "; context. response. write (msg);} public bool IsReusable {get {return false ;}}}
Another handler. ashx is as follows:
<%@ WebHandler Language="C#" Class="Handler" %>using System;using System.Web;public class Handler : IHttpHandler { public void ProcessRequest (HttpContext context) { string callbackName = context.Request.Params["callbackFun"]; string msg = callbackName+ "({\"name\":\"kim\",\"age\":\"18\"});"; context.Response.Write(msg); } public bool IsReusable { get { return false; } }}
2. Ajax cannot implement cross-origin requests
The script var requestUrl = "http://qxw1192430265.my3w.com/kimhandler.ashx"; window. onload = function () {document. getElementById ("btnAjax "). onclick = function () {var xhr = new XMLHttpRequest (); xhr. open ("get", requestUrl, true); xhr. setRequestHeader ("If-Modified-Since", 0); xhr. onreadystatechange = function () {if (xhr. readyState = 4 & xhr. status = 200) {var res = xhr. responseText; alert (res) ;}} xhr. send (null) ;}} script
Check the monitor and no request style is returned.
3. use the script tag to implement cross-origin requests
The test code is as follows: