Detailed decryption of jsonp cross-origin request_javascript skills

Source: Internet
Author: User
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:

     

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.