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('&');
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 the load
event of the Image
object, 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.
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() { //出错 }
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!