jquery .get返回奇数结果

时间:2017-07-26 18:48:48

标签: javascript jquery

我正在使用jquery $ .get读取文本文件。我有以下代码。

console.log("before the get");
$.get("testfile.txt", function(data){
   console.log("in the get");
   console.log(data);
});
console.log("after the get");

在控制台中,我希望看到

before the get
in the get
'...the data...'
after the get

相反,我正在

before the get
after the get
in the get
'...the data...' 

为什么我得到奇怪的订单?谢谢。

2 个答案:

答案 0 :(得分:2)

这并不奇怪。这是正常的,因为get请求是异步的。接到电话后的其他代码不会等待get的完成并继续执行。

完成get调用后,您必须打印控制台日志消息。

console.log("before the get");
$.get("testfile.txt", function(data){
   console.log("in the get");
   console.log(data);
   console.log("after the get");
});

答案 1 :(得分:-2)

我希望你阅读这些文件: aysnc:false

http://api.jquery.com/jquery.ajax/

它会告诉请求关闭异步

我希望这会有所帮助

所以,改为使用 $。ajax()而不是$ .get()

相关问题