简体   繁体   中英

How to return a variable(string) from Ajax using only vanilla Javascript

How to return a variable(string) from Ajax using only vanilla Javascript I am trying to use Ajax to return a string. But when I print the string, it returns Undefined.

Ajax code:

 function loadDoc() { var output; var code; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { output = this.responseText; var parseOutput = JSON.parse(output); // The output we get is in JSON format code = '<table style="width:100%">'; for (var i = 0; i < parseOutput.records.length; i++){ code = code +'<tr>' +'<td style="display:flex; flex-wrap: wrap; border:1px solid grey; border-radius: 25px;">'+'<div style="margin:0.5em;">' +'ITEM : ' + parseOutput.records[i].skuID +'</div>' //+....other fields +'</td>' +'</tr>'; } code = code + '</table>'; //document.getElementById(EIS).innerHTML = code; (If i just print the variable code in here, the result can be shown) return code; }; xhttp.open("GET", "http://localhost/eis/api/skus/read.php", true); xhttp.send(); } 

I would like to output the variable code in another function:

  function output_result(){ var code = loadDoc(); $wrapper.append('<div class="new_crew_form_wrapper">' + '<div class="general_header">Add From XXX System</div>' + '<div class="general_status"></div>' + '<p id="XXX">Test</p>' + code); // I would like the result (variable) of Ajax to be inserted here } 
If i just print the variable code in here, the result can be shown. However, if I want to return the variable code from Ajax, it becomes undefined. How can I fix this? Thank You. Please do not give answers that use jQuery. Thank You.

The "return code;" statement is not returning from loadDoc(), it is returning from the onreadystatechange function, which will go nowhere. You might want this:

// change 
function loadDoc() {
// to
function loadDoc(func1) {

// change
return code;
// to
func1(code);

// then
function output_result() {
  loadDoc(function(stuff) { 
    $wrapper.append('<div class="new_crew_form_wrapper">'
    + '<div class="general_header">Add From XXX System</div>'
    + '<div class="general_status"></div>'
    + '<p id="XXX">Test</p>'
    + stuff);
  } )
}

EDIT: Corrected it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM