


Ajax cross-domain call webservice implementation code_javascript skills
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?

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

Ajax is not a specific version, but a technology that uses a collection of technologies to asynchronously load and update web page content. Ajax does not have a specific version number, but there are some variations or extensions of ajax: 1. jQuery AJAX; 2. Axios; 3. Fetch API; 4. JSONP; 5. XMLHttpRequest Level 2; 6. WebSockets; 7. Server-Sent Events; 8, GraphQL, etc.
