Recently, Ajax encountered cross-domain problems when visiting webservice. Search for information online and summarized them as follows (many of them think they have copied them well)
<<Use JSON to transfer data, rely on JSONP to cross-domain>>
First, I will add 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:
/// <summary> /// Get status data information//// </summary> /// <returns></returns> [WebMethod] public void getElevatorStatusJsonData() { List<List<DeviceInfo>> elevatordatas = new List<List<DeviceInfo>>(); List<SendDicdate> searchList = XmlSerializeHelper.XmlDeserializeFromFile<List<SendDicdate>>(@ConfigUtil.servicePath + ConfigUtil.getConfigByKey("xmlPath") + "Query directive 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# server, and the following is the Java side. 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 parameters through url and pass the parameter name of the jsonpCallback parameter. It is difficult to pronounce, and in simple terms:
jsonp: ""
jsonpCallback:""
By the way: In the chrome browser, you can also set the header information context.Response.AddHeader("Access-Control-Allow-Origin", "*"); on the server to achieve the purpose of cross-domain requests, and there is no need to set the following parameters of ajax
dataType : "jsonp", jsonp: "callbackparam", jsonpCallback:"jsonpCallback1"
Data can be obtained in normal ajax request mode.
The following is the principle. It feels very reasonable when you read what others explained:
1. A well-known problem. Ajax directly requests ordinary files with no permission to access across domains. No matter if you are a static page, dynamic web page, web service, or WCF, as long as it is a cross-domain request, it will not be correct;
2. However, we found that when calling js files on the web page, they are not affected by whether they are cross-domain (not only that, we also found that all tags with the attribute "src" have cross-domain capabilities, such as
3. So it can be judged that at this stage, if you want to access data across domains through pure web (ActiveX controls, server proxy, future HTML5 Websockets, etc., it is to try to load the data into a js format file on the remote server for client to call and further processing;
4. We happen to know that there is a pure character data format called JSON that can concisely describe complex data. What's even better is that JSON is natively supported by js, so the client can process data in this format almost as you wish;
5. This solution is coming out. The web client calls the js format file (usually with JSON as the suffix) dynamically generated on the cross-domain server in the same way as the calling script. It is obvious that the reason why the server wants to dynamically generate JSON files is to load the data needed by the client.
6. After the client successfully calls the JSON file, he obtains the data he needs. The rest is to process and display it according to his own needs. This way of obtaining remote data looks very similar to AJAX, but it is actually different.
7. In order to facilitate the client to use data, an informal transmission protocol has been gradually formed. People call it JSONP. One of the key points of this protocol is to allow users to pass a callback parameter to the server. When the server returns data, it will use this callback parameter as a function name to wrap the JSON data, so that the client can customize its own functions to automatically process the return data.
It is easy for smart developers to think that as long as the js script provided by the server is dynamically generated, the caller can pass a parameter and tell the server "I want a piece of js code that calls the XXX function, please return it to me", so the server can generate the js script and respond according to the client's needs.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title></title><script type="text/javascript">// The callback function after obtaining the flight information query result var flight flight Handler =function(data){ alert('The flight result you query is: piao price'+ data.price +' Yuan, '+'Yu piao '+ data.tickets +' Zhang. '); }; // Provide the url address of the jsonp service (regardless of the type of address, the final return value is a piece of javascript code) var url ="http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998&callback=flightHandler"; // Create a script tag and set its attributes var script = document.createElement('script'); script.setAttribute('src', url); // Add the script tag to the head, and the call starts //document.getElementsByTagName('head')[0].appendChild(script); </script></head><body></body></html><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Untitled Page</title><script type="text/javascript" src=jquery.min.js"></script><script type="text/javascript"> jQuery(document).ready(function(){ $.ajax({ type: "get", async: false, url: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998", dataType: "jsonp", jsonp: "callback",//Passed to the request handler or page to obtain the parameter name of the jsonp callback function name (generally default is: callback) jsonpCallback:"flightHandler",//Customized jsonp callback function name, default is the random function name automatically generated by jQuery, or you can write "?", jQuery will automatically process data for you success: function(json){ alert('You query flight information: piao price: '+ json.price +' yuan, and piao: '+ json.tickets +' Zhang.'); }, error: function(){ alert('fail'); } }); }); </script></head><body></body></html>Isn't it a bit strange? Why didn't I write the function flightHandler this time? And it actually ran successfully! Haha, this is the credit of jQuery. When jquery handles jsonp type ajax (I can't help but complain. Although jquery also classifies jsonp into ajax, they are actually not the same thing), it will automatically generate a callback function and take out the data for the success attribute method to call it. Isn't it very good?