Premise: Sometimes it is necessary to load data on another website on a Web page. or load a page on another site. JS Ajax requests do not have cross-domain capabilities and can be implemented using jquery.
Web-side JS code:
$(function() {$.ajax ({type:"Get", Async:false, URL:"Http://localhost:13964/getpage.ashx?callback=?",//the server-side URL that returns a section of JS data. To return HTML, simply organize the HTML into JSON, such as {"HTML": "DataType: "Jsonp",//indicates that the request is a cross-domain Jsop requestJSONP: "Htmlcall",//The effect is unknown. Just fill it out, but it'll work.Jsonpcallback: "Htmlcallback",//This value replaces the callback parameter value in the URL, such as replacing callback= with Callback=htmlcallbackSuccessfunction(JSON) {$ (json.selector). Append (json.html); }, Error:function(XMLHttpRequest, Textstatus, Errorthrown) {alert (' Fail '); alert (textstatus); alert (Errorthrown); } });});
Service-Side code:
PublicvoidProcessRequest (HttpContext context) {context. Response.ContentType= "Text/plain"; String HTML=string. Empty; Using (FileStream FS=NewFileStream (AppDomain.CurrentDomain.BaseDirectory + "/temppage.html", FileMode.OpenOrCreate)) {using (StreamReader SR=NewStreamReader (FS)) {HTML=Sr. ReadToEnd (); }} JavaScriptSerializer JSS=NewJavaScriptSerializer (); Jsonp JSP=NewJsonp (); Jsp.html=html; String JSON=JSS. Serialize (JSP); //It is important to note that the JSONP is not going to return a standard JSON format, but a format like the one below //Callbackname (JSON) where Callbackname is a parameter from the JS end. JSON is JSON data with no fewer parentheses. String callback = Context. Request["Callback"]; Context. Response.Write (Callback+ "(" + JSON + ")"); public class Jsonp {public string HTML {get; set;} public string Selector= "Body"; }