Home  >  Article  >  Web Front-end  >  Ajax cross-domain call webservice implementation code_javascript skills

Ajax cross-domain call webservice implementation code_javascript skills

WBOY
WBOYOriginal
2016-05-16 09:00:231915browse

recently, ajax encountered cross-domain problems when accessing webservice. i searched for information online and summarized it as follows (many of them were copied from other people’s summaries that they thought were good)

>

let’s start with 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:

 /// 
 /// 获取状态数据信息
 /// 
 /// 
 [webmethod]
 public void getelevatorstatusjsondata()
 {
 list> elevatordatas = new list>();
 list searchlist = xmlserializehelper.xmldeserializefromfile>(@configutil.servicepath + configutil.getconfigbykey("xmlpath") + "查询指令信息.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 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 client's jsonp parameter is used to pass parameters through the url, and the parameter name of the jsonpcallback parameter is passed. it is a bit confusing, but in layman's 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 side to achieve the purpose of cross-domain requests. and there is no need to set the following ajax parameters

 

datatype : "jsonp",
  jsonp: "callbackparam",
  jsonpcallback:"jsonpcallback1"

data can be obtained through normal ajax request.

the following is the principle. after reading what others have explained, it seems to make sense:

1. a well-known problem, ajax direct request for ordinary files has the problem of cross-domain unauthorized access. regardless of whether you are a static page, dynamic web page, web service, or wcf, as long as it is a cross-domain request, it is not allowed;

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

3. it can be judged that at the current stage, if you want to access data across domains through the pure web side (activex controls, server-side proxies, and future html5 websockets are not included), there is only one possibility, and that is to remotely access data. the server tries to load the data into a js format file for client calling and further processing;

4. we happen to already know that there is a pure character data format called json that can describe complex data concisely. what’s even better is that json is also natively supported by js, so the client can process data in this format almost as desired. ;

5. in this way, the solution is ready. the web client calls the js format file dynamically generated on the cross-domain server (usually with json as the suffix) in exactly the same way as calling the script. it is obvious that the reason why the server needs the purpose of dynamically generating a json file is to load the data required by the client into it.

6. after the client successfully calls the json file, it will obtain the data it needs. the rest is to process and display according to its own needs. this method of obtaining remote data looks very much like ajax. , but it’s actually not the same.

7. in order to facilitate the client to use data, an informal transmission protocol has 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, and then the server returns the data. this callback parameter will be used as a function name to wrap the json data, so that the client can customize its own function to automatically process the returned data.

smart developers can easily think that as long as the js script provided by the server is dynamically generated, the caller can pass a parameter to tell the server "i i want a piece of js code that calls the xxx function, please return it to me." then the server can generate a js script according to the client's needs and respond.


Untitled Page

isn't it a little strange? why didn't i write the flighthandler function this time? and it actually worked successfully! haha, this is the credit of jquery. when jquery handles jsonp type ajax (i still can’t help but complain, although jquery also classifies jsonp into ajax, they are really not the same thing), it automatically generates it for you. isn’t it great to call back the function and take out the data for the success attribute method to call?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn