理解/使用回调函数的问题

时间:2014-01-03 22:11:51

标签: javascript php ajax xml

this讨论和聊天中,我明白回调是唯一的方法!

” 从服务器获取一个带有ajax的链接,在变量中写入链接,用这个链接打开一个xml,用xml做一些东西:回调是唯一的方法吗? “

我正在努力了解回调是什么。我读了一些博客,但我仍有问题。

我现在在JS中所拥有的是

1)打开xml的函数。

2)在第一个函数

中请求xml链接的函数

有人可以在PLAIN JAVASCRIPT中提供如何嵌套这两个函数的例子吗?

服务器生成xml的链接,因为我正在建立一个多用户网站,每个用户都拥有自己的xml。所以我需要询问服务器什么是xml的链接然后打开它。有没有一种简单的方法来实现这一目标?我需要普通的javascript没有jquery。 谢谢!

4 个答案:

答案 0 :(得分:2)

通常,“回调”是一个函数,它将在异步过程完成后执行。

因此,您可以从定义从服务器检索数据时应该发生的功能开始(“第二”功能,直观地说,但是您应该首先定义它,因为它是您希望实现的业务功能而不是只是一个实施问题)。简单的事情:

var doSomethingWithTheData = function () {
    // do, well, something with the data
};

这假定您拥有尚未提供的数据。但AJAX调用将获得该数据。您现在可以使用此函数作为AJAX调用的回调。拿AJAX example from MDN,您可能会这样:

var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = doSomethingWithTheData;
// perform the AJAX request

执行和完成AJAX调用后,httpRequest对象将包含服务器的响应。 (请记住,这是异步发生的,因此它不会在下一行代码中包含响应。它将在稍后的某个时间内无法控制。因此需要回调。)

我建议您阅读完整的MDN文章以获取所有详细信息,尤其是处理错误等问题。但是你正在寻找的数据(假设没有出错)将在httpRequest.ResponseText。因此,假设您的变量的范围允许这样做(您可以根据需要进行修改):

var doSomethingWithTheData = function () {
    var data = httpRequest.ResponseText;
    // do, well, something with the data
};

答案 1 :(得分:1)

对不起,@大卫

var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, 
   httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
   httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "http://myserver.mydomain/getMyUsersXMLUrl?user=pete";
httpRequest.open("GET", url, true); // next ajax to retrieve XML - File
httpRequest.onreadystatechange = function() {
   if (httpRequest.readyState == 4) { // response received
      var response = httpRequest.responseText; // this should contain you url

      httpRequest.open("GET", response, true); // next ajax to retrieve XML - File
      // and the same as for the first request
   }
}

答案 2 :(得分:0)

如果您只需要下载xml,则不需要回调。只需看看jquery和ajax。无法从服务器检索回调。 JSONP确实处理了服务器调用的回调(实际上它们不是)Butter你不需要它。我想你是在传递xhttprequestobject

答案 3 :(得分:0)

callback function只是一段可执行代码,作为参数传递给另一段代码。例如:

function first (arr, predicate) {
    // no predicate supplied, return first element
    if (!predicate) return arr[0];

    for (var i = 0; i < arr.length; i++) {
        // return first element satisfying predicate
        if (predicate(arr[i])) return arr[i];
    }

    // no element satisfying predicate, return null
    return null;
}

// second parameter is an anonymous function
// will alert 4, as it's the first element which will return true
alert(first([1, 2, 3, 4, 5, 6], function(n) { return n > 3; }));

回调对于异步任务或在运行时需要额外自定义的库函数非常有用。

相关问题