Answer the question
In order to leave comments, you need to log in
How to rewrite ajax request to pure js (XMLHttpRequest)?
How to rewrite this code to vanilla js? In particular, I'm interested in how and in what form to transfer the data object using XMLHttpRequest with the POST method.
$.ajax({
method: 'POST',
url: url,
dataType: 'json',
data: {
search: value
},
success: function(data) {
console.log(data);
}
});
Answer the question
In order to leave comments, you need to log in
https://good-code.ru/ajax-zapros/
Well, yes, of course, we are not too lazy to google for you
var data = JSON.stringify({ search: value });
var xhr = new XMLHttpRequest();
xhr.open( 'POST', url );
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.send( data );
xhr.addEventListener( 'readystatechange', function(){
if( xhr.readyState !== 4 ) return;
if( xhr.status === 200 ){
console.log( xhr.responsetext ); // ответ в консоль
} else {
console.log( xhr.statusText );
}
});
async () => {
const req = await fetch( url, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify({ search: value })
});
if( req.ok){
const res = await req.json(); // .text(), .blob()...
console.log( res ); // ответ в консоль
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question