Using jquery Jsonp to implement Ajax cross-domain request. Net *.handler and WebService, returning JSON data

Source: Internet
Author: User

1: Cross-domain request handler general handler

usingSystem;usingSystem.Collections.Generic;usingsystem.web;usingSystem.Web.Services;namespacecrossdomain{/// <summary>    ///Summary description of $codebehindclassname $/// </summary>[WebService (Namespace ="http://tempuri.org/")] [WebServiceBinding (ConformsTo=Wsiprofiles.basicprofile1_1)]  Public classHandler:ihttphandler { Public voidProcessRequest (HttpContext context) {context. Response.ContentType="Text/plain"; stringCallbackmethodname = context. request.params["Jsoncallback"]; stringCurrentCity = context. request[" City"]; CurrentCity=string. IsNullOrEmpty (currentcity)?"Beijing":"Shenyang"; stringresult = Callbackmethodname +"({/"city/":"+"/""+ currentcity +"/", /"datetime/":"+"/""+ DateTime.Now +"/"});"; Context.        Response.Write (Result); }         Public BOOLisreusable {Get            {                return false; }        }    }}

Front page:

<!DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "><HTMLxmlns= "http://www.w3.org/1999/xhtml" ><Head>    <title></title>        <Mce:scripttype= "Text/javascript"language= "JavaScript"src= "Js/jquery-1.4.4.js"mce_src= "Js/jquery-1.4.4.js"></Mce:script>    <Mce:scripttype= "Text/javascript"language= "JavaScript"src= "Js/jquery-1.4.4.js"mce_src= "Js/jquery-1.4.4.js"></Mce:script>    <Mce:scripttype= "Text/javascript"language= "JavaScript"><!--        $ (document). Ready (function () {//var Clienturl = "http://localhost:4508/Handler.ashx?jsoncallback=?";        var clienturl = "http://192.168.120.179:8086/Handler.ashx?jsoncallback=?"        var currentcity = "Harbin";                $.ajax ({url:clienturl, DataType: "Jsonp", data: {city:currentcity},        Success:onsuccess, error:onerror});        });        function onsuccess (JSON) {$ ("#data"). HTML ("City:" + json.city + ", Time:" + json.datetime);            } function OnError (XMLHttpRequest, Textstatus, errorthrown) {Targetdiv = $ ("#data"); if (Errorthrown | | textstatus = = "Error" | | textstatus = = "ParserError" | | textstatus = "notmodified") {T Argetdiv.replacewith ("An error occurred while requesting data!                ");            Return } if (textstatus = = "Timeout") {Targetdiv.replacewith ("Request data Timeout!                ");            Return   }        } //   -</Mce:script></Head><Body><DivID= "Data"></Div></Body></HTML>

2:webservice as the target for cross-domain requests:

usingSystem;usingSystem.Collections.Generic;usingsystem.web;usingSystem.Web.Services;namespacecrossdomain{/// <summary>    ///Summary description of $codebehindclassname $/// </summary>[WebService (Namespace ="http://tempuri.org/")] [WebServiceBinding (ConformsTo=Wsiprofiles.basicprofile1_1)]  Public classHandler:ihttphandler { Public voidProcessRequest (HttpContext context) {context. Response.ContentType="Text/plain"; stringCallbackmethodname = context. request.params["Jsoncallback"]; stringCurrentCity = context. request[" City"]; CurrentCity=string. IsNullOrEmpty (currentcity)?"Beijing":"Shenyang"; stringresult = Callbackmethodname +"({/"city/":"+"/""+ currentcity +"/", /"datetime/":"+"/""+ DateTime.Now +"/"});"; Context.        Response.Write (Result); }         Public BOOLisreusable {Get            {                return false; }        }    }}

Page code:

<!DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "><HTMLxmlns= "http://www.w3.org/1999/xhtml" ><Head>    <title></title>        <Mce:scripttype= "Text/javascript"language= "JavaScript"src= "Js/jquery-1.4.4.js"mce_src= "Js/jquery-1.4.4.js"></Mce:script>    <Mce:scripttype= "Text/javascript"language= "JavaScript"><!--        $ (document). Ready (function () {//var Clienturl = "Http://localhost:4508/WebService.asmx/HelloWorld?json            Callback=? ";            var clienturl = "http://192.168.120.179:8086/WebService.asmx/HelloWorld?jsoncallback=?";            var currentcity = "Harbin";                    $.getjson (Clienturl, {city:currentcity}, function (JSON) {                $ ("#data"). HTML ("City:" + json.city + ", Time:" + json.datetime);        }            );        });        function onsuccess (responsedata) {$ ("#data"). HTML (responsedata.city);            } function OnError (XMLHttpRequest, Textstatus, errorthrown) {Targetdiv = $ ("#data"); if (Errorthrown | | textstatus = = "Error" | | textstatus = = "ParserError" | | textstatus = "notmodified") {T Argetdiv.replacewith ("An error occurred while requesting data!                ");            Return } if (textstatus = = "Timeout") {Targetdiv.replacewith ("request dataTimeout!                ");            Return  }        }    // -</Mce:script></Head><Body><DivID= "Data"></Div></Body></HTML>

Note Configure Webconfig:

    <webservices>          <Protocols>            <Addname= "HttpGet"/>            <Addname= "HttpPost"/>          </Protocols>        </webservices> 

Using jquery Jsonp to implement Ajax cross-domain request. Net *.handler and WebService, returning JSON data

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.