我正在制作一个函数,该函数使用jQuery函数iurl
来获取URL为.get()
的另一页的HTML。
我有这个代码
var data1, data2, data3;
var iurl = 'example.com'; //url to get data from
$.get(iurl, function(response){
let parser = new DOMParser();
let parsedHtml = parser.parseFromString(response, 'text/html');
data1 = parsedHtml.getElementById('id1').value;
data2 = parsedHtml.getElementById('id2').value;
data3 = parsedHtml.getElementById('id3').value;
$(".table-main").append("\<tr\>\<td\>" + data1 + "\<\/td\>\<td\>" + data2 + "\<\/td\>\<td\>" + data3 + "\<\/td\>\<\/tr\>"); //displays the data in a table
console.log("first data1 is " + data1 + " data2 is " + data2 + " data3 is " + data3);
})
alert("something");
console.log(" second data1 is " + data1 + " data2 is " + data2 + " data3 is " + data3);
然后,我得到的输出为
second data1 is <data1> data2 is undefined data3 is undefined
first data1 is <data1> data2 is <data2> data3 is <data3>
但所需的输出是
first data1 is <data1> data2 is <data2> data3 is <data3>
second data1 is <data1> data2 is <data2> data3 is <data3>
我知道我必须在这里使用回调,但是在这种情况下我无法弄清楚。
感谢您的帮助。