Ajax cross-domain call WebService implementation code _javascript tips

Source: Internet
Author: User
Tags httpcontext script tag web services domain server

Recent AJAX access WebService encountered Cross-domain problems, online search materials, summarized as follows (many of them are found to be summed up good copy down)

<< use JSON to pass data, rely on JSONP to cross domain >>

First on my implemented code:

Front-End Code:

$.ajax ({
 type: "Get",
 URL: "http://localhost/Service1.asmx/getElevatorStatusJsonData?jsoncallback=?"),
 dataType: "Jsonp",
 Jsonp: "JSON",
 Data: "",
 success:function (result) {
 var data = eval (result); C9/>for (var i = 0; i < data.length i++) {
 alert (data[i].id + "--" + data[i]. Name);
 }
 ,
 error:function (A, B, c) {
 alert (c);
 }}
 ); 

Service-Side code:

 <summary>///Get Status data information///</summary>///<returns></returns> [WebMethod] public void g Etelevatorstatusjsondata () {list<list<deviceinfo>> Elevatordatas = new list<list<deviceinfo>
 > (); list<senddicdate> searchlist = xmlserializehelper.xmldeserializefromfile<list<senddicdate>> (@
 Configutil.servicepath + configutil.getconfigbykey ("Xmlpath") + "query instruction information. xml", Encoding.UTF8);
 foreach (Senddicdate item in searchlist) {string key = Item.portno + "-" + item.bordrate + "-" + item.sendtype;
 List<deviceinfo> deviceinfolist = (list<deviceinfo>) Context.Cache.Get (key); Elevatordatas.
 ADD (deviceinfolist);
 String result = ""; DataContractJsonSerializer json = new DataContractJsonSerializer (Elevatordatas.
 GetType ()); using (MemoryStream stream = new MemoryStream ()) {json.
 WriteObject (stream, Elevatordatas); result = Encoding.UTF8.GetString (stream.
 ToArray ()); } String Jsoncallback = Httpcontext.currEnt.
 request["Jsoncallback"];
 result = Jsoncallback + ' (' + result + ') ';
 HttpContext.Current.Response.Write (result);

 HttpContext.Current.Response.End ();
 }

C#

The above is the implementation code that calls the C # service side, the following is the Java side, the parameters may be different, but the principle is interlinked

Java:

  

String Callbackfunname = context.  request["Callbackparam"];
Context. Response.Write (Callbackfunname + "([{\ name\": \ "john\"}]);

 PS: The client's JSONP parameters are used to pass the parameter through the URL, passing the parameter names of jsonpcallback parameters, more difficult to speak, popular point:

JSONP: ""

Jsonpcallback: ""

Incidentally: In the Chrome browser, you can also set the header information context on the server side. Response.AddHeader ("Access-control-allow-origin", "*") to achieve the purpose of Cross-domain request, and do not need to set Ajax following parameters

  

DataType: "Jsonp",
jsonp: "Callbackparam",
jsonpcallback: "JsonpCallback1"

Data can be obtained with normal AJAX requests.

The following is the principle, see others explain, feel very reasonable:

1, a well-known problem, Ajax directly request Common files have Cross-domain access to the problem, no matter you are static pages, dynamic Web pages, Web services, WCF, as long as the Cross-domain request, are not allowed;

2, but we also found that the Web page to call the JS file is not affected by whether cross-domain (not only this, we also found that the "src" this attribute of the label has a cross-domain ability, such as

3, it can be judged that the current phase if you want to through the pure web-side (ActiveX control, service-side agent, the future of the HTML5 of the WebSocket, etc.) access to data across the domain is only one possibility, that is, on the remote server to try to put data into the JS format files, For client invocation and further processing;

4, happened to us already know that there is a simple character data format called JSON can be concise description of complex data, even better is that the JSON is JS native support, so the client can almost arbitrary processing this format of data;

5, such a child solution is apparent, the Web client through the same way as the call script, to invoke the dynamically generated JS format file on the Cross-domain server (generally with JSON suffix), it is obvious that the server is to dynamically generate JSON files, The goal is to load the data required by the client into it.

6, the client after the successful call to the JSON file, also obtained their own required data, the rest is in accordance with their own needs for processing and display, the way to obtain remote data looks very much like Ajax, but in fact not the same.

7, in order to facilitate the use of data, the client gradually formed an informal transport protocol, people call it Jsonp, one of the key points of this protocol is to allow users to pass a callback parameter to the server, The server side then returns the data by wrapping the callback parameter as the function name to wrap the JSON data so that the client can customize its own function to automatically process the returned data.

It is easy to think of a smart developer, as long as the service side of the JS script is dynamically generated on the line, so that the caller can pass a parameter to tell the service side "I want a call to the XXX function of the JS code, please return to me," so the server can be in accordance with the needs of the client to generate JS script and response.

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> 

Is

A little strange? Why didn't I write Flighthandler this time? And it worked! Haha, this is the credit of jquery, jquery when dealing with JSONP type of Ajax (still can't help spit slot, although jquery also put Jsonp into Ajax, but in fact they are not the same thing), Is it cool to automatically help you generate callback functions and take the data out for Success property method calls?

Related Article

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.