I am trying to write a simple function to return data from an ajax call. Here is what I have
var mytext = "";
function load(url){
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.send();
xhr.onloadend = function(e){
return xhr.responseText;
}
}
var mytext = load('window.html');
console.log(mytext);
I am stuck, How do I get the returned value? I'ts a function in a function and I am lost:(
There are serveral ways to do that. Since you seems to be new to javascript, you can start with callback
:
function load(url, callback){ var xhr = new XMLHttpRequest(); xhr.onloadend = function(e){ callback(xhr); }; xhr.open('GET', url); xhr.send(); } load('/', function (data) { console.log(data); });
In this example, callback
is a function, and we pass xhr
as a parameter to that function while calling.
My advice is to make use of the Promise
and fetch
APIs.
function ajax(options) {
return new Promise(function (resolve, reject) {
fetch(options.url, {
method: options.method,
headers: options.headers,
body: options.body
}).then(function (response) {
response.json().then(function (json) {
resolve(json);
}).catch(err => reject(err));
}).catch(err => reject(err));
});
}
You can use it like so:
const ajaxResponse = await ajax({url: '/some/api/call', method: 'get'});
In case you don't already know, await
can only be used inside async
functions. If you don't want to use async
functions, do the following:
ajax({url: '/some/api/call', method: 'get'}).then(data => {
// process data here
});
JavaScript is a single-threaded language. This means everything runs in a blocking manner. If your Ajax call takes 3 seconds, then JavaScript will pause for 3 seconds. Luckily, the XMLHttpRequest
and fetch
APIs combat this issue by using asynchronous functions, meaning code can continue running while the Ajax call is awaiting a response.
In your code, you're not getting a response from your function because the Ajax call doesn't stop the execution, meaning by the time the call has been made, there's nothing to return yet and by the time the call is finished, the function's call is long in the past too. You can tell JavaScript however to keep track of this asynchronous task through Promise
s. When your task is finished, the Promise
's then
function is called with the data from the Ajax call.
JavaScript also provides syntactic sugar to make reading asynchronous code easier. When we use an async
function, what we're actually doing is creating a regular function, whose body is wrapped in a Promise
.
This also means that when you want to wait for the result of a previous Promise
, you can prepend await
in front of the Promise
reference and await the completion of the Promise
.
So you may have code that looks like this:
const call = await ajax({ ... });
console.log(call);
which actually translates to the following:
ajax({ ... }).then(call => {
console.log(call);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.