Javascript 在另一个函数完成后调用该函数

Javascript 在另一个函数完成后调用该函数,javascript,jquery,ajax,Javascript,Jquery,Ajax,我正在尝试在load()完成后调用另一个函数。我首先尝试使用alert()进行检查,但是在load()完成之前,我看到了警报。我能够在load()函数中成功加载内容。但是,alert()为空 $(document).ready(function(){ load(); $.when(load()).done(function(){ alert((document.getElementById('item').innerHTML)); });

我正在尝试在load()完成后调用另一个函数。我首先尝试使用alert()进行检查,但是在load()完成之前,我看到了警报。我能够在load()函数中成功加载内容。但是,alert()为空

$(document).ready(function(){   

    load();
    $.when(load()).done(function(){
        alert((document.getElementById('item').innerHTML));
    });        

    function load()
    { 
        $("#item").load("/somepage.aspx", function (response, status, xhr){
              if ( status == "error" ) {
                var msg = "error: ";
                $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
              }
        });                         
    };
});
您需要
load()
返回一个承诺,然后将此承诺传递给
$

.load()
不返回承诺,它返回调用它的jQuery集合(用于链接目的)。您可以改为使用
$重写
load()
。get()
,它返回一个
jQXHR
,它实现了
延迟
(这是jQuery的promise类)

实际上,您不需要使用
$。当
时,您可以编写:

p.done(function() { ... });

您可以使用回调函数并将代码更新为以下内容

$(document).ready(function(){   

    load(function(){
        alert((document.getElementById('item').innerHTML));
    });

    function load(callback)
    { 
        $("#item").load("/somepage.aspx", function (response, status, xhr){
              if ( status == "error" ) {
                var msg = "error: ";
                $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
              }
              if(callback) {
                   callback();
              }
        });                         
    };
});
您可以使用已经在大多数主流浏览器中实现的新API

var jsonPromise = new Promise(function(resolve, reject) {
    // do a thing, possibly async, then…

    if ( /* everything turned out fine */ ) {
        resolve("Stuff worked!");
    } 
    else {
        reject(Error("It broke"));
   }
});

jsonPromise.then(function(data) {
    console.log(result); // "Stuff worked!"
}, function(err) {
    console.log(err); // Error: "It broke"
});

看来你是对的。我想它就像其他AJAX速记功能一样。现在它工作了很多。在somepage.aspx中,我使用$.ajax调用web服务并返回我附加在该页面中的数据。现在,当我使用load()上传数据时,即使可以看到数据内容,也无法获取任何元素。有解决方案吗?我不知道你在问什么,最好是在新问题中发布详细信息。但首先阅读:使用前面显示的方法,如何仅检索.aspx页面的内容。比如说,id为p的div内容。thnks。
var jsonPromise = new Promise(function(resolve, reject) {
    // do a thing, possibly async, then…

    if ( /* everything turned out fine */ ) {
        resolve("Stuff worked!");
    } 
    else {
        reject(Error("It broke"));
   }
});

jsonPromise.then(function(data) {
    console.log(result); // "Stuff worked!"
}, function(err) {
    console.log(err); // Error: "It broke"
});