preface

With the development of the Web so far, the usual way of data transmission is through Ajax data communication. There are many other ways to communicate besides using Ajax to transfer JSON. This article will introduce the methods and types of Web data transfer in terms of requesting data, sending data, and data formats.

Request Data

This is usually an action taken when the Web requests a resource from the server.

XMLHttpRequest

XMLHttpRequest is by far the most common technology that allows requests to be sent asynchronously. XMLHttpRequest is the cornerstone of AXIOS. It can be used like this:

const url = 'https://blog.gdccwxx.com'
const req = new XMLHttpRequest();

req.onreadystatechange = () = > {
    if (req.readyState === 4) { // request done
        const responseHeader = req.getAllResponseHeaders();
        const data = req.responseText;
        console.log(data);
    }
    if (req.readyState === 3) { // requesting
        const responseHeader = req.getAllResponseHeaders();
        const data = req.responseText;
        console.log('requesting', data); }}; req.open('GET', url, true);
req.setRequestHeader('X-Requested-With'.'XMLHttpRequest');
req.send(null);
Copy the code

Create the request instance with new XMLHttpRequest(); Send requests using the open() and send() methods; ReadyState indicates the request status, 3 being requested and 4 being completed. Onreadystatechange () to listen for changes in the status of the request, by listening for readyState to determine the current status of the request.

Use the GET method whenever possible for behavior that only retrieves data and does not change the state of the service. Because GET request methods are cached. There is a performance improvement for the same request. POST is required only when the URL request is close to or larger than 2048 bytes. Some browsers truncate urls with excessive length.

At the same time, his support is also very friendly, almost every major browser manufacturers support very high. It is the best way to get data asynchronously.

Fetch

The FETCH API is more elegant than the XMLHttpRequest for event listening. Its promise-making approach is syntactically concise and supports scenarios such as Service Workers and Cache APIS.

Feel the simplicity of use:

const data = await fetch('https://blog.gdccwxx.com', {
    method: 'GET'.'Content-Type': 'text/plain'});console.log('data', data);
Copy the code

The first argument to fetch represents the REQUESTED URL; The second parameter represents the configuration item, which configures the request method, response content type, and so on.

Its support, while not as good as XMLHttpRequest, is adequate for basic scenarios. Perfect solution for demo pages.

Dynamic script injection

Dynamic script injection is an anomaly compared to the two conventional approaches above. The biggest benefit of this approach is that it overcomes the biggest limitation of XHR: the ability to request data across domains. It can be done like this:

// index.html
const scriptElement = document.createElement('script');
scriptElement.src = 'http://127.0.0.1:5500/lib.js';
document.getElementsByTagName('head') [0].appendChild(scriptElement)

function jsonCallback(jsonString) {
  console.log('requested! ', jsonString);
}


/ / 127.0.0.1:5500 / lib. Js
jsonCallback({ status: 'success' });
Copy the code

Such as:

The features of this use case are:

  • HTML files are local static files
  • Lib files are cross-domain files

However, while this technique solves the cross-domain problem, dynamically injected code has full control over the entire page. This includes modifying web content, redirecting to other sites, etc. So be careful when importing code from outside sources.

Multipart XHR

Multipart XHR allows clients to transfer multiple resources from the server with a single HTTP request. It does this by packaging the resource on the server into a long, mutually agreed string split. This string is then processed in JS and parsed based on the MIME-type and other header information passed in.

HTTP2 static push is similar to HTTP2 static push, the difference is that HTTP2 static push according to the resource level active push, no JS parsing; Multipart XHR packages files into a single file that is parsed in JS on the browser side.

This approach can be completely replaced by HTTP2, but the mindset of reducing HTTP handshakes in order to reduce resource requests is worth learning from.

Sending Data

Sometimes you don’t care about receiving data, just sending it to the server. Such as sending reports, behavior logging, catching errors, etc. There are two widely used technologies when data only needs to be sent to the server: XHR and beacons.

XMLHttpRequest or Fetch

GET is used for small amounts of data, because GET requests usually send only one packet, whereas POST sends two, including header information and body information. Large amounts of data use POST, and extremely long urls are truncated.

Beacons

This technique is very similar to dynamic script injection, using JS to create the Image object and setting the SRC property to the reported URL, which contains the key-value pair data to be returned via GET.

const url = 'https://blog.gdccwxx.com';
const params = [ 'result=true']

(new Image()).src = `${url}?${params.join('&')}`;
Copy the code

The server receives the data and saves it without any feedback. This is the most efficient way to send messages to the server because the performance cost is small and the client is not affected at all by server errors.

But because it’s so simple, it means there’s a limit to what you can do.

  • Unable to sendPOSTThe data,URLLength bound
  • You can accept data from the server, but it’s limited. For example, by listening inimageThe width of the etc.

Beacons are a perfect solution if you don’t need a lot of data uploaded to the server and you don’t need to worry about the response body. If so, XMLHttpRequest and FETCH are better choices.

Data Formats

When considering data transmission technology, data transmission speed must be considered. The size of the same data varies in different data formats, so how to choose the data format becomes the key to the transmission speed.

XML

XML was chosen as the universal data format at the beginning of Ajax’s popularity, and it had many advantages: excellent versatility and a format that was so strict and easy to verify that almost all servers supported XML at the time.

Here is an XML example:

<? The XML version = "1.0" encoding = "utf-8" ><user id="gdccwxx">
    <username>gdccwxx</username>
    <email>[email protected]</email>
    <blog>blog.gdccwxx.com</blog>
</user>
Copy the code

XML is verbose compared to other formats, and the syntax is a little fuzzy. During parsing, you must know the layout of the XML before you can understand its meaning. And it’s not easy to parse:

function parserXML(xml) {
    const user = xml.getElementsByTagName('user') [0];
    const id = user.getAttribute('id');
    const username = user.getElementsByTagName('username') [0].nodeValue ?? ' ';
    // ...
}
Copy the code

JSON

JSON is a lightweight and easily parsed data format that uses JavaScript objects. Represents the same data format:

{
  "user": {
    "id": "gdccwxx"."username": "gdccwxx"."email": "[email protected]"."blog": "blog.gdccwxx.com",}}Copy the code

It’s very simple to convert to JS Object, native JS:

function parseJSON(text) {
  return eval(` (${text}) `);
}

// or

JSON.parse(text);
Copy the code

The JSON format is a very general and concise format.

HTML

HTML is not only presented as a page, it is also a format for data transfer. Although it is a more bloated data format, it is even more complex than XML. However, it is a good choice for page server rendering. Here’s an example of a data transfer:

<ul>
  <li class="user" id="gdccwxx">
    <span>gdccwxx</span>
    <a href="mailto:[email protected]">[email protected]</a>
    <a href="https://blog.gdccwxx.com">blog.gdccwxx.com</a>
  </li>
</ul>
Copy the code

Custom format

The ideal data structure should contain only the necessary structures that can be easily wrapped up. Such as:

1:gdccwxx; [email protected]; blog.gdccwxx.comCopy the code

This data structure is very compact and can be downloaded very quickly, much simpler than any generic structure.

Resolution:

function parseCustomType(str) {
  const [, content] = str.split(':');
  const [user, mail, blog] = content.split('; ');
  return { user, mail, blog };
}
Copy the code

However, this approach is not universal, and it is a good solution for some businesses that require extreme speed.

It is easy to tell from morphology that their transmission speed is in the following order:

Custom format > JSON > XML > HTMLCopy the code

The commonality is as follows:

JSON > XML > HTML > Custom formatCopy the code

The JSON type performs well in terms of generality and transfer speed, and almost wins in comparison.

conclusion

Compared to the uncertainties of the Web age 10 years ago, our age is looking at the world on the shoulders of giants. But also because of the growing uniformity of Web requests, the modern Web lacks a lot of flexibility.

Remember some time ago and the client side experts chat, he said that now the Web is more and more like the client, and the client is more and more web-based. Got me thinking: What will the Web look like in 10 years? Is it the agility of the web2.0 era? Or is it facebook client-side completeness? Time will tell

Thank you for reading here at 💗

If you are interested, you can come and play on my blog