Javascript 使用 jquery 获取 URL 内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32163159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:42:04  来源:igfitidea点击:

Get URL content using jquery

javascriptjqueryurlcurl

提问by barej

I am reading content of a local file using jqueryand I get undefined.

我正在使用读取本地文件的内容,jquery我得到undefined.

I feel the problem is related to synchronization of URL loading. But I don't have any idea about how to fix this code:

我觉得问题与 URL 加载的同步有关。但我不知道如何修复此代码:

function url_content(url)
{
    var content;
    $.get(url,function( data ) {content=data});
    return content;
}


var content=url_content("local_templates/template1.html");
alert(content);

回答by leaf

Asynchronous vs Synchronous

异步与同步

The "A" in "Ajax" is for "Asynchronous". The underlying meaning of this word was hard to figure out for me, I know it can take some time to become familiar with, but it's a critical subject in modern web development and computing in general, hence it's worth a little effort.

“Ajax”中的“A”代表“异步”。这个词的基本含义对我来说很难弄清楚,我知道它可能需要一些时间来熟悉,但它是现代 Web 开发和一般计算中的一个关键主题,因此值得花点功夫。

Most of the time your code runs in a synchronousway, thus you don't have to worry about whether your environment is ready or not. Considering the following code, it's obvious that "v" is ready for being used at the time you need it, you don't have to waitfor it to be initialized.

大多数时候您的代码以同步方式运行,因此您不必担心您的环境是否准备就绪。考虑下面的代码,很明显“v”已经准备好在你需要它的时候使用它,你不必等待它被初始化。

var v = 1;     // no delay during initialization
var u = v + 1; // you can use "v" immediately

Even if there was a delay at this point, a synchronous processing would wait for the instruction to be done before executing the next line. Hence, you can be sure that "v" will be ready when you'll need it. Now, let's see how this code behaves if we introduce an asynchronous task.

即使此时有延迟,同步处理也会在执行下一行之前等待指令完成。因此,您可以确定“v”将在您需要时准备就绪。现在,如果我们引入一个异步任务,让我们看看这段代码的行为。

function ajax (url) {
    // 1. go to url asynchronously
    // 2. bring back the value
    // 3. return the value
};
var v = ajax('mywebsite.com'); // undefined
var u = v + 1; // "v" is not ready -> NaN

The way the tasks are numbered reflects what's going on in your mind, but it's not correct, actually 3 happens before 2. Roughly speaking, ajax()won't get the value fast enough and returns before the first task completes, hence, the value is not available and the program fails.

任务编号的方式反映了您的想法,但这是不正确的,实际上 3 发生在 2 之前。粗略地说,ajax()不会足够快地获取值并在第一个任务完成之前返回,因此,该值不是可用并且程序失败。

More precisely, the program starts talking to a remote computer as soon as ajax()is called. Such a task can last a couple of seconds, but the program is aware of its asynchronous nature, hence, it doesn't wait for the result and jumps to the next line immediately.

更准确地说,程序一ajax()被调用就开始与远程计算机对话。这样的任务可以持续几秒钟,但程序知道它的异步性质,因此,它不会等待结果并立即跳转到下一行。

Now I think you should better understand what's going on. The main point is that a program isn't necessarily executed in a single flow, there might be some tasks executed apart from the rest, in parallel. If you are still confused, take some time to think of it before going further :-)

现在我认为你应该更好地了解发生了什么。重点是程序不一定在单个流程中执行,可能有一些任务与其他任务分开执行,并行执行。如果您仍然感到困惑,请在继续之前花一些时间考虑一下:-)

How to deal with asynchronous tasks ?

如何处理异步任务?

So, how to avoid crashing your program while performing asynchronous tasks ? Using callbacks. A callback is a function which is passed to another function as a parameter and called internally. Let's see how to fix the previous code block with a callback :

那么,如何在执行异步任务时避免程序崩溃?使用回调。回调函数是作为参数传递给另一个函数并在内部调用的函数。让我们看看如何使用回调修复前面的代码块:

function ajax (url, callback) {
    // 1. go to url asynchronously
    // 2. bring the value
    // 3. when previous tasks done, do callback(value)
};
ajax('mywebsite.com', function (value) {
    var v = value;
    var u = v + 1;
});

To fully understand how it works, you need to know that there is an internal mechanism which acts as a middle man between your program and the remote computer. As soon as the response of the remote computer is available, this mechanism calls the callback function.

要完全理解它是如何工作的,您需要知道有一个内部机制充当您的程序和远程计算机之间的中间人。只要远程计算机的响应可用,此机制就会调用回调函数。

Well, I think it's enough for now, I won't bother you no more ;-) For details you should browse jQuery's docs on Ajax, it can be a good place to start. As a conclusion, here is a possible implementation of ajax()(not bullet proof). Enjoy.

好吧,我认为现在已经足够了,我不会再打扰您了 ;-) 有关详细信息,您应该浏览jQuery 的 Ajax 文档,这是一个很好的起点。作为结论,这是ajax()(非防弹)的可能实现。享受。

function ajax (url, callback) {
    var req = new XMLHttpRequest();
    req.open('GET', url, true); // true = asynchronous
    req.onload = function () {
        var value = JSON.parse(this.responseText);
        callback(value);
    };
    req.send(null);
}

Additional stuffs (click to zoom)

其他内容(点击放大)

Synchronous : the main flow is paused during remote queries.

同步:在远程查询期间主流程暂停。

Asynchronous : the main flow keeps going during remote queries.

异步:主要流程在远程查询期间继续运行。

回答by Ryan

Its because of the asynchronous nature of javascript. You have to wait for the data to come back before you can use it. You would need to do something like this:

这是因为 javascript 的异步特性。您必须等待数据返回才能使用它。你需要做这样的事情:

function url_content(url){
    return $.get(url);
}


url_content("local_templates/template1.html").success(function(data){ 
  alert(data);
});

or just

要不就

$.get("local_templates/template1.html").success(function(data){ 
  alert(data);
  doSomeStuffWithTheResult(data);
});


function doSomeStuffWithTheResult(content) {
  // code that depends on content goes here...
}

If you absolutely must keep in synchronous you can do this(NOT RECOMMENDED)

如果你绝对必须保持同步,你可以这样做(不推荐)

function getRemote(remote_url) {
    return $.ajax({
        type: "GET",
        url: remote_url,
        async: false
    }).responseText;
}

jQuery: Performing synchronous AJAX requests

jQuery:执行同步 AJAX 请求

回答by Shatadip

".success" might not work and result in an error, try with ".then":

“.success”可能不起作用并导致错误,请尝试使用“.then”:

  var url="local_templates/template1.html";
  $.get(url).then(function(data){ alert(data); });