gpt4 book ai didi

javascript - JavaScript/Node 中如何调用它?

转载 作者:行者123 更新时间:2023-11-28 17:49:57 29 4
gpt4 key购买 nike

我将发布两个简单示例,我想知道它们是如何命名的

$.post('/path/to/file', {param1: 'value1'}, function(data, textStatus, xhr) {
/*optional stuff to do after success */
});

post函数中还有第三个参数,它是一个函数,但是函数内可以使用data、textStatus和xhr,那怎么调用呢?即使我一直使用它们,我觉得我仍然不理解“用法”或整个事情,我的意思是,第三个参数如何返回或使内部函数的这三个参数可用?

最佳答案

$.post (以及 $.get$.ajax 等)是 jQuery 在 XMLHTTPRequest API 之上的“糖”。第三个参数,即函数,称为回调,一旦请求完成并以请求响应作为其参数,就会调用该函数。简化版本如下所示:

function post(endpoint, params, callback) {
var http = new XMLHttpRequest();
var url = endpoint;
var params = params;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {

// The callback is called with the text (and other parameters)
// passed in as arguments
// jQuery also returns textStatus, and the jQXHR object
// https://api.jquery.com/jquery.post/
callback(http.responseText));
}
}
http.send(params);
}

它的使用方式与$.post完全相同。

post('http://example.com/post', {}, function (text) {
console.log(text);
});

关于javascript - JavaScript/Node 中如何调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45785148/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com