Native JS for Ajax and Ajax cross-domain requests

Source: Internet
Author: User

Objective

Now, in the front-end of the procedure ape, if, do not understand some of the data in front and back of the knowledge of the interaction, it is not too shy to say that they are the program ape. Of course, there are many frameworks today, and there are corresponding methods for data interaction between the front and back tables.

And, among them, the most used should Sue is the Ajax of jquery. Today, however, the shadow introduces you to native JS Ajax and cross-domain requests.



First, the Ajax of jquery

First, let's recall the Ajax notation of jquery:

$.ajax ({    URL:,    type: ',    dataType: ',    data: {              },    success:function () {             },    error: function () {              }})


Second, native JS implementation ajax
First step: Get XMLHttpRequest object var ajax = new XMLHttpRequest ();                Step two: Set the state listener function Ajax.onreadystatechange = functions () {console.log (ajax.readystate);                Console.log (Ajax.status); Fifth step: In the listener function, Judge readystate=4 && status=200 to indicate that the request was successful if (ajax.readystate==4 && ajax.status==200) {//Sixth step: Accept the response data using ResponseText, Responsexml, and use the native JS operation Dom to display the Console.log (ajax.respons                    EText);                    Console.log (ajax.responsexml);//return is not XML, display null Console.log (Json.parse (Ajax.responsetext));                Console.log (eval ("+ajax.responsetext+"));                        }}//Third step: Open a link ajax.open ("GET", "H51701.json", false);//true asynchronous request, false synchronous Fourth step: Send a request. You can send an object and a string without passing data to send null ajax.send (NULL);


Comments:

1. The open (method, URL, async) methods require three parameters:

Method: Methods used to send requests (get or post), get is simpler and faster than post, and can be used in most cases, however, use the POST request in the following cases:

    • Unable to use cache file (update file or database on server)
    • Send a large amount of data to the server (POST has no data volume limit)
    • Post is more stable and more reliable than GET when sending user input with unknown characters

URL: A URL that specifies the server-side script, which can be any type of file, such as. txt and. xml, or server script files, such as. asp and. PHP (capable of performing tasks on the server before returning the response));

Async: Specifies that the request should be asynchronous (true) or synchronous (false), and true to execute additional scripts while waiting for the server to respond, to process the response when the response is ready, and false to wait for the server to respond and execute.

2. The Send () method can send the request to the server.

3. onReadyStateChange: There is a function that handles the response of the server, and the onreadystatechange function is executed whenever readyState changes.

4. ReadyState: The status information of the server response is stored.

    • 0: Request not initialized
    • 1: Server Connection established
    • 2: Request received
    • 3: In Request processing
    • 4: The request is complete and the response is ready

5. ResponseText: Gets the response data in the form of a string.


eval ( ) and Json.parse ()

In addition, we introduce two methods of parsing strings:

Eval ():

The eval function is used to parse the JS code in the string and execute it!!
When parsing a JSON string using the Eval function, you need to stitch the JSON string inside the function ()
For example: eval ("(" +json1+ ")")
Indicates that the string in the Eval function is not for execution, but for string parsing
That
Eval ("(" +json1+ ")") = Json.parse (json1;

Josn.parse ():

Pure parsing of JSON strings into arrays or objects;

Iv. cross-domain requests for Ajax


First, we need to know why there is a cross-domain request, and under what circumstances will there be cross-domain requests?

1 homologous policy

The same-origin policy restricts how a document or script loaded from one source interacts with a resource from another source. This is a key security mechanism for isolating potentially malicious files.

It is defined as:

A script requests data back to the table, only the data belonging to the same protocol name, the same host name, and the same port number are read;

Therefore, when requesting different protocol names, different port numbers, and files under different host names,
Will violate the same-origin policy, unable to request success, need to cross-processing!!

2 ways to resolve cross-domain requests


method One: background php to set up

Front desk does not need any settings, in the background is requested PHP file, write a header.

Header ("access-control-allow-origin:*");

--- indicates which domain names are allowed to request this PHP file,* indicates that all domain names are allowed

JS Code:

          

Comments:

Where the URL is the path to the PHP file;

PHP Code:

          

Results:

  

method Two: implement cross-domain using SRC attribute + jsonp


Implementation steps:

1, the original SRC attribute label sub-band cross-domain function; You can use the SRC attribute of the script tag to request background data

<script src= "http://127.0.0.1/json.php" ></script>

2, for SRC after loading the data successfully, will be loaded directly into the script tag;

Therefore, returning the JSON string directly from the background cannot be resolved in the script tag.

Therefore, the background should return a callback function name to the foreground and pass the JSON string as a parameter.

Back in the background php file: Echo "callback ({$json})";

3. The foreground receives the callback function that is returned and will be called directly in the script tag. Therefore, it is necessary to declare such a callback function as a callback for the successful request

  function callback (data) {  alert ("Request succeeded!!!");  Console.log (data);  }

JS Code:

            

            

PHP Files:

            

Results:

            


method Three: Ajax implementation of jquery Jsonp

1, in the AJAX request, set datatype to "JSONP";

2, back in the background, still need to return the callback function name, however, Ajax when sending a request, the default is to use a GET request to send the callback function name to the background,

Background $_get[' callback '] Remove function name:

---echo "{$_get[' callback '} ({$str})";

3, back in the background, the foreground can use the Ajax success function as a successful callback

---success:function (data) {}

JS Code:

        

PHP Files:       

          

Results:

  

of course, the background can also casually return a function name, the foreground as long as the request succeeds, it will automatically call this function. Similar to the second ②, ③ step, without the need for this method of step ③

PHP return: echo "callback ({$STR})";

JS Code: function Callback (data) {

Console.log (data);

}

JS Code:

        

PHP Files:

          

Results:

        

Although, the shadow is a Web front-end engineer, but, in the shadow of the thought about the data interaction this piece, for us this group of people, to use the place is still, more, moreover, even if it is not used, more than a skill to the body is also good;

Well, today, the shadow of the share, it ends here, thank you for your support!!!!

Native JS for Ajax and Ajax cross-domain requests

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.