Home >Web Front-end >JS Tutorial >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:232044browse

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:

 /// <summary>
 /// 获取状态数据信息
 /// </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") + "查询指令信息.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 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.

<!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">// 得到航班信息查询结果后的回调函数var flightHandler =function(data){
 alert('你查询的航班结果是:piao价 '+ data.price +' 元,'+'余piao '+ data.tickets +' 张。');
 }; // 提供jsonp服务的url地址(不管是什么类型的地址,最终生成的返回值都是一段javascript代码)var url ="http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998&callback=flightHandler"; // 创建script标签,设置其属性var script = document.createElement('script');
 script.setAttribute('src', url); 
 // 把script标签加入head,此时调用开始 
//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",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback) jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据 success: function(json){
 alert('您查询到航班信息:piao价: '+ json.price +' 元,余piao: '+ json.tickets +' 张。');
 },
 error: function(){
 alert('fail');
 }
 });
 }); </script></head><body></body></html>

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