如何仅使用vanilla Javascript从Ajax返回变量(字符串)

时间:2018-06-07 03:52:03

标签: javascript ajax

如何仅使用vanilla Javascript从Ajax返回变量(字符串) 我试图使用Ajax返回一个字符串。但是当我打印字符串时,它返回Undefined。

Ajax代码:



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();

}
&#13;
&#13;
&#13;

我想在另一个函数中输出变量代码:

&#13;
&#13;
	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
	}
&#13;
&#13;
&#13; 如果我只是在这里打印变量代码,则可以显示结果。但是,如果我想从Ajax返回变量代码,它将变为未定义。我怎样才能解决这个问题?谢谢。 请不要给出使用jQuery的答案。谢谢。

1 个答案:

答案 0 :(得分:0)

“返回代码”;语句不是从loadDoc()返回的,它是从onreadystatechange函数返回的,它将无处可去。你可能想要这个:

// 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);
  } )
}

编辑:更正了。