JavaScript---Beacons image beacons send data

一个新手
Release: 2017-09-09 10:33:24
Original
1572 people have browsed it


Introduction

This technique is very similar to dynamic script injection. Use JavaScript to create a new Image object and set the src attribute to the script URL on the server. The The URL contains the key-value pair data we want to return via GET. Please note that the img element is not created or inserted into the DOM.

var url = '/status_tracker.php';var params = [ 'step=2', 'time=1248027314' ] (new Image()).src = url + '?' + params.join('&');
Copy after login

The server will receive the data and save it, it does not need to be sent to the client Any feedback message, so no picture will actually be displayed. This is the most efficient way to send information back to the server. Its performance cost is very small, and server-side errors will not affect the client at all.

Pictures A beacon is simple, but that also means it's limited in what it can do. You can't send POST data, and URLs have a maximum length, so the length of data you can send is limited quite a bit. You can receive the server The data returned, but is limited to very few ways. One way is to listen to theloadevent of theImageobject, which will tell you whether the server successfully received the data. You also You can check the width and height of the image returned by the server (if it is an image) and use these numbers to inform you of the status of the server. For example, a width of 1 means "success", and a width of 2 means "retry".

If you do not need to return data in the response, you should send a 204 No Content status code without the message body. It will prevent the client from continuing to wait for the message body that never comes.

Example

var url = '/status_tracker.php';var params = [ 'step=2', 'time=1248027314' ] var beacon = new Image(); beacon.src = url + '?' + params.join('&'); beacon.onload = function( ) { if (this.width == 1) { //成功 } else if (this.width == 2) { //失败 } } beacon.onerror = function() { //出错 }
Copy after login

The above is the detailed content of JavaScript---Beacons image beacons send data. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!