Метод fetch() делает сетевой запрос схожим образом с ajax() и get() методами в jQuery.
Файл js:
let request = {
run : function( url, data )
{
let headers = {
'Content-Type': 'application/json;charset=utf-8',
};
fetch( url, {
'method': 'POST',
'mode': 'same-origin',
'credentials': 'include',
'cache': 'no-cache',
'headers': headers,
'body': JSON.stringify( data )
})
.then( response => this.check( response ) )
.then( data => this.success( data ) )
.catch( error => this.error( error ) );
},
check : function( response )
{
if( response.status !== 200 )
{
console.log('Похоже, возникла проблема. Код состояния: ' + response.status );
return;
}
return response.json();
},
success : function( data )
{
if( data.result )
{
console.log( data.html );
// > ваш юзерагент
}
},
error : function( error )
{
console.log('Ошибка: ', error );
}
};
let url = 'handler.php';
let data = {
'ua': window.navigator.userAgent
};
request.run( url, data );
Файл-обработчик handler.php:
$res = [
'result' => false,
'html' => '',
];
$contentType = isset( $_SERVER['CONTENT_TYPE'] ) ? trim( $_SERVER['CONTENT_TYPE'] ) : '';
if( $contentType === 'application/json;charset=utf-8' )
{
$content = trim( file_get_contents('php://input') );
$data = json_decode( $content, true );
$res['result'] = true;
$res['html'] = $data['ua'];
}
echo json_encode( $res );
Комментарии
0Нашли ошибку или хотите дополнить материал?