When I use Google chrome dev console to run my code I have some problems. My current page is vk.com. I use this code
var request_url = 'https://vk.com/dev/openapi';//similar domain
var requestData = function(request_url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', request_url, true);
xhr.onreadystatechange = function() {
if(xhr.readyState==4 && xhr.status==200) {
var content = xhr.responseText;
console.log(callback(content))
callback(content);
}
}
xhr.send();
};
var dataEl = requestData(request_url, function(content) {
var el = document.createElement( 'html' );
el.innerHTML = content;
return el;
});
it does not work because dataEl is undefined but console.log show me ... ei what I want.
if code like this is used:
var requestData = ...(similar)
var contentNew = requestData(request_url, function(content){return content});
var el = document.createElement( 'html' );
el.innerHTML = contentNew;
el is not empty or undefined object. It's what I want.
How should I use XHR without manual input?
It doesn't make sense to return
from a callback , either chain more callbacks or make your code event driven.
Other than that and some old coding styles, your only mistake seemed to be trying to set el.innerHTML = dataEl;
when you seemed to want el.innerHTML = content;
Here is a demo of using an XMLHttpRequest
function xGET(url, callback, error_callback) {
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', callback);
if (error_callback)
xhr.addEventListener('error', error_callback);
xhr.open('GET', url);
xhr.send();
return xhr; // why not?
};
var my_url = '/'; // for demo
xGET(my_url, function () {
var el;
// creating a <html> doesn't make much sense
// this example will use a <div> instead
el = document.createElement('div');
// do something with your XHR's data
el.textContent = this.responseText;
// do something with `el`
document.body.appendChild(el);
}, function () {
var el = document.createElement('div');
el.textContent = 'Something went wrong :(';
document.body.appendChild(el);
});
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.