Use XmlHttpRequest and "cross-domain" problem solving

After a. IE7 xmlHttpRequest creation of objects on different browsers are compatible.

     The following approach is to consider the compatibility of the actual project generally used Jquery ajax request may not consider compatibility issues .

function getHttpObject() {
var xhr=false;
if (windows.XMLHttpRequest)
    xhr=new XMLHttpRequest();
else if (window.ActiveXObject)
{
    xhr=new ActiveXObject("Microsoft.XMLHttp");
}
return xhr;
}
 

 

 

II. Properties and methods of XMLHttpRequest

1, the method described
abort () Stops the current request
the getAllResponseHeaders () all response header as a key / value pairs returned HTTP request
to return the specified key getResponseHeader ( "header") header string value
open ( "method", "url ") to establish calls to the server, Method can be GET, POST or pUT, URL can be relative or absolute the URL of
the send (Content) sends a request to the server
setRequestHeader ( "header", "value ") to specify the header to the value provided. Before setting any headers must call open ()


2, attribute describes
onreadystatechange every state change triggers, usually a javascript function calls
state readyState request, five values; 0: initialization, 1: Loading; 2: loaded, 3: interaction, 4: complete
responseText server response, expressed as a string
in response responseXML server, expressed in XML, DOM object can be resolved to
an HTTP status code status server (200: ok, 304: not modified, 404: Not Found etc.)
the statusText the Http status code corresponding text (ok or Not Found)

 

3, an example of a handwritten Ajax request:

  eg1: get
$(function(){
      $("#id").onclick(tunction(){
          var request=new XMLHttpRequest();
          var url="http://www.baidu.com";
          var method="GET";    
          request.open(method,url);
          request.send(null);
          request.onreadystatechange=function(){
             if (request.readyState==4&&(request.status==200 || request.status==304))
                alert (request.reponseText);
                // If it returns html tags, you can use 
          //$("#id2").innerHtml=request.reponseText;
                // If the return xml format, the results need to be getElementByTagName ( "") [index] Analytical 
         //alert(request.reponseXML.getElementByTagName("")[index])
 
          /*var type=request.getResponseHeader("Content-Type");
                if(type.indexOf("xml") !== -1 && request.responseXML){ 
                    callback(request.responseXML); //Document对象响应
                }else if(type=== 'application/json'){
                    callback(JSON.parse(request.responseText)) //JSON响应
                }else {
                    callback(request.responseText);
                }*/
} }) })
 
  eg2: post
<script type="text/javascript">
    var xhr = new XMLHttpRequest();
    xhr.timeout = 3000;
    xhr.ontimeout = function (event) {
        alert("请求超时!");
    }
    var formData = new FormData();
    formData.append('tel', '18217767969');
    formData.append('psw', '111111');    xhr.open('POST', 'http://www.test.com:8000/login');
    xhr.send(formData);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
        else {
            alert(xhr.statusText);EG3: synchronization response
</ Script>
    }
        }


    // synchronous response 
    // initiate synchronous HTTP GET request to obtain the contents of the specified URL 
    // returns the response text, or if the request is unsuccessful or not the text on the error response. 
    getTextSync function (URL) { 
        var = new new Request the XMLHttpRequest (); 
        the request.open ( "the GET", URL, to false); // open to the fasle passed as the third parameter (), then the send () method will block until request is complete 
        request.send (null); 

        IF (request.status 200 is ==!) the throw new new Error (request.statusText); 

        var = request.getResponseHeader type ( 'the type-the Content'); 
        IF (type.match (/! text ^ /)) the throw new new Error ( "the Expected Textual respomse; GOT:" + type); 

        return request.responseText; 
    }

 

III. Cross-Origin Resource Sharing (CORS)

XMLHttpRequest HTTP request can be issued to a different domain name server, called CORS

solution:

1), to allow cross-domain server: response headers need to add the following options

     CORS head missing "Access-Control-Allow-Origin ", on behalf of the error: the server refused to cross-domain access. If this error occurs, you need to set the server to allow cross-domain requests .

void the doGet protected (the HttpServletRequest Request, the HttpServletResponse Response) throws ServletException, IOException { 
    response.setCharacterEncoding ( "UTF-. 8"); 
    the response.setContentType ( "text / HTML; charset = UTF-. 8"); 
    // * denotes allow any domain Cross-domain access 
    response.setHeader ( "access-Control-the Allow-Origin", "*"); 
    // specify a particular domain can access 
    response.setHeader ( "access-Control-Allow -Origin", "http: localhost: 8080 / "); 
    // data 
    List <Student> studentList getStudentList = (); 
    the JSONArray JSONArray = JSONArray.fromObject (studentList); 
    String jsonArray.toString Result = (); 
    // pass over the front end of the callback function name 
    String callback = request.getParameter ( "callback");
    result = callback + "(" + result + ")";




    // return the parcel data by a callback function name, so that data is returned to the callback function as a parameter passed back

    response.getWriter().write(result);
}

  

2), JSONP, jsonp disadvantages, get request can only be sent

The following approach is to consider the compatibility of the actual project generally used Jquery ajax request may not consider compatibility issues.

EG1: How to use the <script src = ""> a cross-domain request to complete
reception:

<% @ Page the pageEncoding = "UTF-. 8" contentType = "text / HTML; charset = UTF-. 8" Language = "Java"%>
<HTML>
<head>
<title> cross-domain test </ title>
<Script the src = "JS / jQuery-1.7.2.js"> </ Script>
<Script>
// callback
function showData (Result) {
var the JSON.stringify Data = (Result); // JSON object into a string of
$ ( "#text") Val (Data);.
}

$(document).ready(function () {

. $ ( "BTN #") the Click (function () {
// input to the head of a script, the script initiates a cross-domain requests
$ ( "head") append ( "<script src = 'http:. // localhost ?: 9090 / Student the callback = showData '> <\ / Script> ");
});

});
</script>
</head>
<body>
<input id="btn" type="button" value="跨域获取数据" />
<textarea id="text" style="width: 400px; height: 100px;"></textarea>

</body>
</html>

 
Backstage:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");

//数据
List<Student> studentList = getStudentList();


JSONArray jsonArray = JSONArray.fromObject(studentList);
String result = jsonArray.toString();

// pass over the front end of the callback function name
String = request.getParameter the callback ( "the callback");
// return a callback function package name data, such data is returned as a parameter to the callback function to pass back
result = callback + "( "+ result +") ";

response.getWriter().write(result);
}

 

 

eg2: jquery way of cross-domain request jsonp

--- code-behind or above

<%@ page pageEncoding="utf-8" contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>跨域测试</title>
<script src="js/jquery-1.7.2.js"></script>
<script>

$(document).ready(function () {

$("#btn").click(function () {

.ajax $ ({
URL: "HTTP: // localhost: 9090 / Student",
type: "the GET",
dataType: "JSONP", // specify the data type returned by the server
Success: function (Data) {
var = the JSON Result .stringify (data); // json object into a string
$ ( "# text") Val (Result);.
}
});

});

});
</script>
</head>
<body>
<input id="btn" type="button" value="跨域获取数据" />
<textarea id="text" style="width: 400px; height: 100px;"></textarea>

</body>
</html>

 3), to build a gateway system

 

Other attached:

Here window.onload and reinserted at $ (function ({})) difference ($ (document) .ready (function () {})) is:

1. window.onload must wait until the images included in the page finished loading all the elements to perform

    $ (function () {}) is a DOM performed after texture mapping is completed, without waiting loaded .

2. Write the number of different

    window.onload can not write more, if there are multiple window.onload method will only execute a

    $ (function () {}) can be written simultaneously a plurality of, and are performed to obtain

3. Simplified wording

    window.onload no shorthand method, may be used $ (window) .load (function () {}) instead of

    $ (Function () {}) is actually $ (document) .ready (function () {}) Abbreviation Method

    $ (Window) .load (() {} function), IE is not only in the case of the frame, are performed after $ (function () {}) under normal circumstances.

 

Guess you like

Origin www.cnblogs.com/651434092qq/p/11109199.html