Implementation Code of ajax cross-origin webservice call _ javascript skills

Source: Internet
Author: User
This article mainly introduces examples and understandings of ajax cross-origin webservice calling. Recently, ajax has encountered cross-origin problems when accessing webservice. The following is a summary of the Cross-origin problems encountered during ajax access to webservice, search for information on the Internet, summarized as follows (many people think that the summary is a good copy)

< <用json来传数据,靠jsonp来跨域> >

First, go to 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); for (var i = 0; i < data.length; i++) { alert(data[i].ID + "--" + data[i].Name); } }, error: function (a, b, c) { alert(c); } }); 

Server code:

////// Obtain status data information //////
 [WebMethod] public void getElevatorStatusJsonData () {List
 
  
> Elevatordatas = new List
  
   
> (); List
   
    
SearchList = XmlSerializeHelper. XmlDeserializeFromFile
    
     
> (@ ConfigUtil. servicePath + ConfigUtil. getConfigByKey ("xmlPath") + "query command information. xml ", Encoding. UTF8); foreach (SendDicdate item in searchList) {string key = item. portno + "-" + item. bordrate + "-" + item. sendtype; List
     
      
DeviceInfoList = (List
      
        ) 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 for calling the c # server. The following is the java end. The parameters may be different, but the principles are the same.

Java:

  

String callbackFunName = context.Request["callbackparam"];  context.Response.Write(callbackFunName + "([ { \"name\":\"John\"}])");

 PS: The jsonp parameter of the client is used to pass the parameter name of the jsonpCallback parameter through the url. It is more popular:

Jsonp :""

JsonpCallback :""

Note: In the chrome browser, you can also set the header information context on the server. response. addHeader ("Access-Control-Allow-Origin", "*"); to achieve cross-Origin requests, and do not need to set the following ajax Parameters

  

dataType : "jsonp",  jsonp: "callbackparam",  jsonpCallback:"jsonpCallback1"

Data can be obtained in normal ajax request mode.

The following is the principle. I think it makes sense to look at what others have explained:

1. A well-known problem is that Ajax directly requests common files without cross-domain access permissions. Render Manager determines that you are a static page, dynamic webpage, web Service, and WCF, as long as it is a cross-domain request, no;

2. However, we found that when calling js files on the web page, it is not affected by cross-origin (not only that, we also found that all tags with the "src" attribute have cross-domain capabilities, such

3. It can be determined that in the current stage, cross-Origin data access is only possible if you want to access data through pure web (ActiveX control, server proxy, Websocket that belongs to HTML5 in the future, that is to say, on the remote server, try to put data into js files for the client to call and further process;

4. We already know that there is a pure character data format called JSON that can describe complex data in a concise manner. Even better, JSON is also supported by js native, therefore, the client can process data in this format as needed;

5. In this way, the solution is ready. The web client uses the same method as the calling script to call the js format files dynamically generated on the Cross-origin server (generally with the suffix of JSON). Obviously, the purpose of the server to dynamically generate a JSON file is to load the data required by the client.

6. After the client successfully calls the JSON file, it obtains the required data. The rest is to process and present the data as needed, this method of obtaining remote data looks like AJAX, but it is actually not the same.

7. In order to facilitate the use of data on the client, an informal transmission protocol is gradually formed, which is called JSONP. One key point of this Protocol is to allow users to pass a callback parameter to the server, then, when the server returns the data, the callback parameter is wrapped in JSON data as the function name, so that the client can customize its own function to automatically process the returned data.

Smart developers can easily imagine that as long as the js scripts provided by the server are dynamically generated, in this way, the caller can pass a parameter and tell the server that "I want a js Code to call the XXX function. Please return it to me ", as a result, the server can generate js scripts and respond to the requirements of the client.

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.