Scripted HTTP for JavaScript client JavaScript (via XMLHttpRequest)

Source: Internet
Author: User
Tags http post

the XMLHttpRequest object is designed to handle responses that consist of plain text or XML, but one response can also be a different type if the user agent (UA) supports this type of content.  

Most of the client-side JavaScript that is browsed includes this feature.

The HTTP protocol specifies how a Web browser can request documents from a Web service, how to deliver form content to a Web server, and how to respond tothese requests and delivery. the Web browser handles a lot of HTTP (usually HTTP is not under the control of the script)1. Users click on a link2. Submit a Form3. Enter a URL usually JavaScript code can script http, but not always. such as setting the window.location of an objectDownload Images Download Documents <iframe>download Script execution <script> src properties when the script sets these properties to a URL, an HTTP GET request is initiated to download the contents of the URL. It is therefore possible to encode information into the URL query string portion of an image and set a src attribute torouted to the Web server. (Note: The Web server must actually return an image (any size such as: 1px*1px transparent map)so using the above method, it is possible to script HTTP, but the portability is poor. in modern browsers, XMLHttpRequest objects are well supported and provide full access to the HTTP protocol ,includes the ability to make post and Hedad requests as well as normal get requests. Requests that can be returned synchronously or asynchronously to the Web server.and can return content in the form of text or a DOM document. (can receive any form of text document)The XMLHttpRequest object is a key feature of the Web application architecture called Ajax.  20.1 using XMLHttpRequest (the new version is XMLHttpRequest 2)There are 3 steps to using its scripted HTTP1. Create a XMLHttpRequest object2. Specify an HTTP request and submit to a Web server3. Get the server's response synchronously or asynchronously such as: Var request=new XMLHttpRequest (); Use the Open () method to specify the method and URL of the requestRequest.open ("GET", url,false);get POST HEAD in a wayURL of the URL Web serverThe last parameter is whether to specify if asynchronous, True async (default), False to synchronize In addition to the above 3 optional parameters, there are 4th and 5th parameter optional parameters, name and passwordThese two parameters are required when obtaining a URL from a server that requires authorization.  open () does not actually send a request to the Web server, it simply saves its own parameters and then uses it when the request is actually sent later. before sending a request, you must set all required headers for the request. such as:Request.setrequestheader ("User-agent", "XMLHttpRequest");setRequestHeader ("Accept-language", "en");setRequestHeader ("");Note: Web browsers automatically add related cookies for established requests only if you want to send a fake cookie to the server, you need to explicitly set the "cookie" header Finally, the request is sent to the server. request.send (NULL)The parameter of the Send () function is the body of the request. For HTTP get requests, parameters are generally always null (whether there can be non-null parameter bodies) Note: XMLHttpRequest is a client object whose methods do not allow the omission of parameters like the core JavaScript function(at least Firefox is the case) 20.1.3 Get a synchronous responseSend () does not return a status code. Once it returns, you can use the Request object's Status property to check the HTTP status code returned by the server. This code may have a value defined in the HTTP protocolStatus 200: request succeededState 404: The requested URL does not existand so on. You can consult the relevant documentation. The following code is immediately after the Send () function. if (request.status==200){alert (request.responsetext);}Else{}Note: The XMLHttpRequest object also provides access to the returned HTTP headergetResponseHeader () 20.1.4 Processing a synchronous response the asynchronous response from the server is like an asynchronous mouse click from the user: it needs to be notified when it happens. This is accomplished by an event handle.On The onReadyStateChange property, the event handle function is called as long as the readystate changes. readystate is an integer value that specifies the state of an HTTP request.  table 20-1 Value of XMLHttpRequest readystatereadyState meaning0 Open () not yet called1 open () has been called, but send () has not yet been called2 Send () has been called, but the server has not yet responded3 data is being received from the server. ReadyState 3 is slightly different in Firefox and Internet Explorer.  Note: In contrast to most events in client JavaScript, no event object is passed to the onreadystatechange handle,and the XMLHttpRequest object is not passed as a parameter to the event handle, so you have to directly access it inside the handle functionobject declared by XMLHttpRequest (within its valid range) such as:request.onreadystatechange=function (){if (request.readystate==4)        {if (request.status==200                {alert (requst.responsetext);                }        }} Note:1, Firefox in the larger download process, the readystate==3 will be called multiple times onreadystatechange handle to provide download process feedback2, IE only when readystate actual changes are called, and responsetext in this state can not be queried.  Safety of 20.1.5 XMLHttpRequestas part of the same-origin security policy, the XMLHttpRequest object can publish HTTP requests only to certain servers. documents that use this object are downloaded through these servers, but you can bypass it if you want, by using aServer-side Scripts act as proxies to receive content from certain offsite URLs. Note: XMLHttpRequest security restrictions have a very important meaning: make HTTP requests and do not work with other URL styles. If you do not work with URLs that use the file://protocol. This means that you cannot test the XMLHttpRequest script from your own local file system. (Must be placed in the Web server) HTTP POSTwith a POST request, the data is passed to the server in the request body instead of being encoded into the URLrequest.send ();question: 1 The format of the client request body 2, the data format returned by the server 20.2.5One disadvantage of the XMLHttpRequest object is that there is no way to provide an expiration value for a specified request, and for a synchronous request,If the server hangs, the Web browser remains blocked in the Send () method, and all processing is frozen. (but asynchronous requests generally do not, but the settings expire better)Workaround: Use settimeout () to set the expiration valuecalls the Xmlhttprequest.abort () method in the handler specified by settimeout to cancel the request.   20.3 AJAXthe key feature of an AJAX application is that it uses scripted HTTP to communicate with a Web server without causing page overloading.  20.3.2 single page applicationonly a page loaded JavaScript-driven Web application is required. implemented using XMLHttpRequest objects and AJAX schemas.  Note: Web applications designed along this line of thinking may contain a small amount of JavaScript startup code. (such as just a start-up animation screen)once started, the startup code uses a Xmlhttpreuqest object to download the actual code for the application, and then the code is combined with the eval () methodexecution. This allows JavaScript code to take over control, load the data required by XMLHttpRequest, and use the DOM to take the data in DHTML formsubmitted to be displayed to the user.  20.3.3 remote Scripting calls RPC4 years earlier than Ajax appeared, the basic idea is the same, set the src= of the IFRAMEif the Web server returns an HTML document that contains a <script> tag, the markup contains JavaScript that will be executed by the browser. and you can call methods that are defined in the window that is contained in the IFRAME. In this form, the server can send a very direct command to its client in the form of JavaScript iframe Cross-access and window.parent accessHow to find a variablestand-alone global execution Environment 20.3.4 The warning about Ajax 3 things to look out for when designing an AJAX application1. Visual Feedback2, URL-related3, using AJAX loading, the content changes, the Address toolbar URL is always the same (forward, Back button invalidation) This is reasonable, because it is a single page application.  20.4 Scripting http with <script> tagsset SRC and set the parameter after the SRC value?dynamic.  

Scripted HTTP for JavaScript client JavaScript (via XMLHttpRequest)

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.