使用jquery获取URL内容 [英] Get URL content using jquery

查看:191
本文介绍了使用jquery获取URL内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jquery 阅读本地文件的内容,并获得 undefined



我觉得问题与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);它是因为javascript的异步性质,因此


解决方案

您必须等待数据恢复才能使用。你需要这样做:

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


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

或只是

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


function doSomeStuffWithTheResult(content){
//取决于内容的代码在这里...
}



如果您绝对必须保持同步,您可以执行此操作(不推荐)

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

jQuery:执行同步AJAX请求


I am reading content of a local file using jquery and I get 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:

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


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

解决方案

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:

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获取URL内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆