A small demo of C # and JSONP easily solve cross-domain access issues with jquery and JSONP

Source: Internet
Author: User
Tags domain server

Customer Service side:

Create a jsonpclient.aspx page below the A project with the following code:

<%@ Page Language="C #"AutoEventWireup="true"codebehind="JsonpClient.aspx.cs"Inherits="webfrom.jsonpclient" %><!DOCTYPE HTML><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Headrunat= "Server">    <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" />    <title></title>    <Scriptsrc= "Http://localhost:16908/Script/jquery-2.1.1.js"></Script>    <Scripttype= "Text/javascript">        $(function() {$ (document). On ("Click", "#btn", function() {$.ajax ({type:'Post', URL:'http://localhost:16908/JsonpServer.aspx',//Note one: Server address data:{name:"Cupid", Age: -}, DataType:'Jsonp', Jsonp:"Callback",//Note two: callback function success:function(data) {
Console.log (data); } }); }); })//Note three: What the callback function should dofunctionCallback (data) {
Data=eval ("(" +data+ ")");
return data; } </Script></Head><Body> <formID= "Form1"runat= "Server"> <Div> <inputtype= "button"ID= "BTN"value= "Tap" /> </Div> </form></Body></HTML>
server-side:

Create a jsonpserver.aspx page below the B project with the following code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingmvcdemoutility;namespace_20150319_wefrom{ Public Partial classJsonpServer:System.Web.UI.Page {protected voidPage_Load (Objectsender, EventArgs e)            {Response.disablekernelcache ();            Response.Cache.SetNoStore (); stringName ="name". Querystrings ();//You can also request.querystring["name". ToSTring ()intAge =" Age". Querystrings ().            ToInt32 (); Response.Write ("Callback (" +string. Format ("{{name:\ ' {0}\ ', Age:{1}}}", Name,age) + ");;
Note Four: The callback name must be JSONP with attention two: "Callback" consistent Response.End (); } }}

Run the server and click View results on the running customer service side

Add a few knowledge

$.ajax ({async:false, Url:http://cross-DomainType: "GET", DataType:' Jsonp ', Jsonp:' Callback ', Data:qsdata, timeout:5000, Beforesend:function(){                                //Jsonp Mode This method is not triggered. The reason may be datatype if you specify JSONP, it's not an AJAX event anymore .}, Success:function(JSON) {//client jquery pre-defined callback function, after successfully obtaining the JSON data on the cross-domain server, will execute this callback function dynamically    if(json.actionerrors.length!=0) {alert (json.actionerrors);   } gendynamiccontent (Qsdata,type,json); }, Complete:function(XMLHttpRequest, Textstatus) {$.unblockui ({fadeOut:10 }); }, Error:function(XHR) {//Jsonp Mode This method is not triggered. The reason may be datatype if you specify JSONP, it's not an AJAX event anymore .    //Request Error HandlingAlert ("Request error (Please check the correlation network condition.)"); }});
Function callback (JSON) {
return JSON;
}

The most basic principle of JSONP is: adding a <script> tag dynamically, and the SRC attribute of the script tag is not a cross-domain limitation. In this way, this cross-domain approach is actually unrelated to the Ajax XMLHttpRequest protocol.
In fact, "jquery Ajax cross-domain problem" has become a pseudo-proposition, jquery $.ajax method name is misleading.

If set to datatype: ' Jsonp ', this $.ajax method has nothing to do with Ajax XMLHttpRequest, instead it is the JSONP protocol.

JSONP is an unofficial protocol that allows the server-side integration of script tags to return to the client, using the form of JavaScript callback for cross-domain access JSONP that is JSON with Padding. Due to the limitations of the same-origin policy, XMLHttpRequest only allows resources to be requested for the current source (domain name, protocol, port). If cross-domain requests are made, we can make cross-domain requests by using the HTML script tag and return the script code to execute in the response, where the JavaScript object can be passed directly using JSON. This cross-domain communication method is called JSONP.

Jsoncallback function jsonp1236827957501 (...): A callback function that is registered by the browser client and gets the JSON data on the cross-domain server

First register a callback (for example: ' Jsoncallback ') on the client, and then pass callback's name (for example: jsonp1236827957501) to the server. Note: After the server gets the value of callback, use jsonp1236827957501 (...). Include the JSON content that will be output, at which point the server generates JSON data to be properly received by the client.

Then, in JavaScript syntax, a function is generated, and the function name is the value jsonp1236827957501 of the parameter ' Jsoncallback ' passed up.

Finally, the JSON data is placed directly into the function in the form of a parameter, so that a document of JS syntax is generated and returned to the client.

The client browser, parses the script tag, and executes the returned JavaScript document, at which time the JavaScript document data, as parameters,
Passed into the client's pre-defined callback function (as in the previous example, the jquery $.ajax () method encapsulates the Success:function (JSON)). (Dynamic execution callback function)

Can say Jsonp way principle and <script src= "//cross-domain/...xx.js" ></script> is consistent (QQ space is a large number of this way to achieve cross-domain data exchange). JSONP is a script injection (scripts injection) behavior, so there are some security implications.

A small demo of C # and JSONP easily solve cross-domain access issues with jquery and JSONP

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.