Ajax introduction _ dynamic node Java school arrangement, ajaxjava

Source: Internet
Author: User

Ajax introduction _ dynamic node Java school arrangement, ajaxjava

AJAX is not a JavaScript specification. It is just an abbreviation of Asynchronous JavaScript and XML, that is, JavaScript is used to execute Asynchronous Network requests.

If you carefully observe the submission of a Form, you will find that once the user clicks the "Submit" button and the Form starts to be submitted, the browser will refresh the page, on the New Page, tell you whether the operation is successful or failed. If the network is too slow or otherwise, you will get a 404 page.

This is how the Web works: an HTTP request corresponds to a page.

If you want to keep the user in the current page and send a new HTTP request, you must use JavaScript to send the new request, receive the data, and then use JavaScript to update the page, the user feels that he is still on the current page, but the data can be constantly updated.

Gmail was the first to use AJAX on a large scale. After a Gmail page is loaded for the first time, all the remaining data is updated based on AJAX.

Writing a complete AJAX code using JavaScript is not complicated, but it should be noted that AJAX requests are executed asynchronously, that is, the response must be obtained through the callback function.
Writing AJAX in modern browsers mainly relies onXMLHttpRequestObject:

Function success (text) {var textarea = document. getElementById ('test-response-text'); textarea. value = text;} function fail (code) {var textarea = document. getElementById ('test-response-text'); textarea. value = 'error code: '+ code;} var request = new XMLHttpRequest (); // create an XMLHttpRequest object request. onreadystatechange = function () {// when the status changes, the function is called back if (request. readyState = 4) {// The response is successfully completed // The response result is: if (request. status = 200) {// success, get the response text through responseText: return success (request. responseText);} else {// failed. Identify the cause of failure based on the response code: return fail (request. status) ;}} the else {// HTTP request is still ...}} // send the request: request. open ('get', '/api/categories'); request. send (); alert ('request sent, please wait for response... ');

For earlier versions of IE, you need to change the ActiveXObject object:

Function success (text) {var textarea = document. getElementById ('test-ie-response-text'); textarea. value = text;} function fail (code) {var textarea = document. getElementById ('test-ie-response-text'); textarea. value = 'error code: '+ code;} var request = new ActiveXObject ('Microsoft. XMLHTTP '); // create a Microsoft. XMLHTTP Object request. onreadystatechange = function () {// when the status changes, the function is called back if (request. readyState = 4) {// The response is successfully completed // The response result is: if (request. status = 200) {// success, get the response text through responseText: return success (request. responseText);} else {// failed. Identify the cause of failure based on the response code: return fail (request. status) ;}} the else {// HTTP request is still ...}} // send the request: request. open ('get', '/api/categories'); request. send (); alert ('request sent, please wait for response... ');

If you want to mix the standard writing method with the IE writing method, you can write it like this:

var request;if (window.XMLHttpRequest) { request = new XMLHttpRequest();} else { request = new ActiveXObject('Microsoft.XMLHTTP');}

Pass DetectionWindowWhether the object existsXMLHttpRequestProperty to determine whether the browser supports standardXMLHttpRequest. Note: Do not useNavigator. userAgentTo check whether the browser supports a JavaScript feature. One is that the string itself can be forged, and the other is that it is very complicated to judge the JavaScript feature through the IE version.

WhenXMLHttpRequestAfter the object, you must first setOnreadystatechange. In the callback functionReadyState = 4Determine whether the request is complete. If the request has been completedStatus === 200Determine whether the response is a successful response.
XMLHttpRequestObjectOpen ()The method has three parameters: GET or POST, URL, and asynchronous. The default value isTrue, So do not write.

Note:Do not specify the third parameterFalseOtherwise, the browser stops responding until the AJAX request is complete. If the request takes 10 seconds, you will find that the browser is in the "suspended" status within 10 seconds.

Finally, the send () method is called to actually send the request. Parameters are not required for GET requests,POSTThe request must pass the body part in a string or FormData object.

Security restrictions

The URL of the code above uses a relative path. If you change itFor 'http: // www.sina.com.cn /'And then run it. An error is certainly returned. In the Chrome console, you can also see the error message.

This is caused by the same-source policy of the browser. By default, when JavaScript sends an AJAX request, the URL domain name must be exactly the same as the current page.

Completely consistent means that the domain name must be the same (Www.example.comAndExample.comDifferent), the Protocol must be the same (http and https are different), and the port number must be the same (default: Port 80, it is different from: 8080 ). Some browsers are loose and allow different ports. Most browsers strictly abide by this restriction.

Is it because JavaScript cannot be used to request URLs from external domains (other websites? There are several methods:

First, you can use the Flash plug-in to send HTTP requests. This method can bypass the browser's security restrictions. However, you must install Flash and interact with Flash. However, Flash is troublesome to use, and the use of Flash is getting fewer and fewer.

Second, a proxy server is set up under the same-source domain name for forwarding. JavaScript is responsible for sending requests to the proxy server:
'/Proxy? Url = http://www.sina.com.cn'
The proxy server then returns the result, so that it complies with the same-source policy of the browser. This method requires additional development on the server.

The third method is called JSONP. It has a limitation that only GET requests can be used and JavaScript requests must be returned. In this way, cross-origin actually uses the browser to allow cross-origin reference of JavaScript resources:

JSONP is usually returned as a function call. For example, the returned JavaScript content is as follows:
Foo ('data ');
In this way, if we have preparedFoo ()Function, and then add a dynamic<Script>Node, which is equivalent to dynamically reading JavaScript resources from external domains, and finally waiting to receive callbacks.

Take the 163 stock query URL as an example for URL: http://api.money.126.net/data/feed/0000001,1399001? Callback = refreshPrice, you will get the following response:
RefreshPrice ({"0000001": {"code": "0000001 ",...});

Therefore, we need to first prepare the callback function on the page:

Function refreshPrice (data) {var p = document. getElementById ('test-jsonp'); p. innerHTML = 'current price: '+ data ['000000']. name + ':' + data ['000000']. price + ';' + data ['000000']. name + ':' + data ['000000']. price ;}

Finally, it is triggered using the getPrice () function:

function getPrice() { var  js = document.createElement('script'),  head = document.getElementsByTagName('head')[0]; js.src = 'http://api.money.126.net/data/feed/0000001,1399001?callback=refreshPrice'; head.appendChild(js);}

Then, data is loaded across domains.

CORS

If the browser supports HTML5, you can use the new CORS policy once and for all.

CORS stands for Cross-Origin Resource Sharing, which is defined in html5.

Before understanding CORS, we should first understand the concept:

Origin indicates the current domain of the browser. When JavaScript initiates a request to an external domain (such as sina.com), the browser first checksAccess-Control-Allow-OriginWhether the domain is included. If yes, the cross-origin request is successful. If not, the request fails and JavaScript cannot obtain any response data.

It is represented by a graph:

Assume that the current domain isMy.comThe external domain isSina.com, As long as the Response HeaderAccess-Control-Allow-OriginIsHttp://my.comOr *. The request is successful.

It can be seen that whether the cross-origin is successful depends on whether the other server is willing to set a correct one for you.Access-Control-Allow-OriginThe decision is always in the hands of the other party.

The above cross-origin request is called a "simple request ". Simple requests include GET, HEAD, and POST (the Content-Type of POST is limited to application/x-Www-form-urlencoded,Multipart/form-dataAndText/plainAnd cannot contain any custom header (for example,X-Custom: 12345), Usually meeting 90% of the requirements.

Whether or not you need to use JavaScript to request resources through CORS, you must understand the principle of CORS. The latest browser fully supports HTML5. When referencing external domain resources, besides JavaScript and CSS, CORS must be verified. For example, when you reference a font file on a third-party CDN:

/* CSS */@font-face { font-family: 'FontAwesome'; src: url('http://cdn.com/fonts/fontawesome.ttf') format('truetype');}

If the CDN service provider is not correctly setAccess-Control-Allow-OriginThe browser cannot load font resources.
For PUT, DELETE, and Other types suchApplication/jsonBefore sending an AJAX request, the browser will first send an OPTIONS request (called preflighted request) to this URL and ask whether the target server accepts the request:
OPTIONS/path/to/resource HTTP/1.1
Host: bar.com
Origin: http://my.com
Access-Control-Request-Method: POST

The server must respond and specify the allowed Method:
HTTP/1.1 200 OK
Access-Control-Allow-Origin:
Http://my.com
Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS
Access-Control-Max-Age: 86400

The browser confirms the Server ResponseAccess-Control-Allow-MethodsThe header does contain the Method of the AJAX request to be sent before the AJAX request is sent. Otherwise, an error is thrown.

Since JSON-format data transmitted in POST or PUT mode is common in REST, to correctly process POST and PUT requests across domains, the server must correctly respond to OPTIONS requests.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.