6
A fetch API is provided in the global window scope in javascript, with the first argument being the URL of your API, itβs Promise-based mechanism.
Simple Example
// url (required)
fetch('URL_OF_YOUR_API', {//options => (optional)
method: 'get' //Get / POST / ...
}).then(function(response) {
//response
}).catch(function(err) {
// Called if the server returns any errors
console.log("Error:"+err);
});
In your case, If you want to receive the JSON response
fetch('YOUR_URL')
.then(function(response){
// response is a json string
return response.json();// convert it to a pure JavaScript object
})
.then(function(data){
//Process Your data
if (data.is_taken_email)
alert(data);
})
.catch(function(err) {
console.log(err);
});
Example using listener based on XMLHttpRequest
function successListener() {
var data = JSON.parse(this.responseText);
alert("Name is: "+data[0].name);
}
function failureListener(err) {
console.log('Request failed', err);
}
var request = new XMLHttpRequest();
request.onload = successListener;
request.onerror = failureListener;
request.open('get', 'https://jsonplaceholder.typicode.com/users',true);
request.send();
Example of Using Listener as setInterval
(Iβm not sure that you want to do something like this, itβs just to share with you)
var listen = setInterval(function() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(function(response) {
return response.json();
})
.then(function(data) {
if (data[0].name)
console.log(data[0].name);
})
.catch(function(err) {
console.log(err);
});
}, 2000);//2 second
I am not familier with Django, but I hope this could help you.
0
this my example to fetch
export function fetchProduct() {
return (dispatch, getState, api) => {
const access_token = localStorage.getItem("access_token");
fetch(`${BASE_URL}/products`, {
method: "GET",
headers: {
"access_token": access_token
}
})
.then((response) => response.json())
.then((jsonData) => {
console.log(jsonData.data, 'isi dari json data line 30');
dispatch(productSetProduct(jsonData.data));
})
.catch((err) => {
console.log(err);
});
};
}```
- [Django]-What's the correct include path in this template?
- [Django]-Applying a Django FilterSet to an Annotated QuerySet?
- [Django]-Django handle newlines in textarea
Source:stackexchange.com