我希望能得到一些帮助,从相当基本的层面理解这段代码中发生的情况。
我知道这基本上是调用指定的 URL。我还知道它应该返回一个 JSON 对象。如果调用成功,则会调用我在下面定义的 displayResults
函数。
displayResults
函数采用单个参数。
$.ajax({
url: wikiAPI,
dataType: "json",
success: displayResults //dont call the function, pass it. it will be called when the response is ready.
});
function displayResults(data){
console.log(data);//here is your response
$(".results").html("<p><h3>Hello World!</h3></p>");
}
最佳答案
您必须了解,在 Javascript 中,函数是“一流的”,这意味着可以像对待任何其他变量一样对待函数:您可以将其作为变量传递给另一个函数,然后从另一个功能。
这在 JavaScript 中大量使用,尤其是作为回调。
当您调用 $.ajax
函数时,您向其提供一个对象作为参数。该对象将包含 ajax 请求不同状态的回调函数——其中之一是成功
。
所以,基本上,成功的关键需要有一个函数类型的值。
现在,当您说 displayResults("response")
时,您正在使用参数 "response"
调用函数 displayResults
--其返回类型不是函数
。
如果您只使用 displayResults
而没有使用 ()
,则您对待该函数的方式与对待任何其他变量的方式完全相同。该函数未执行。
你可以做这样的事情:
var functionAlias = displayResults;
就像任何其他变量一样。
以同样的方式,你可以这样做:
$.ajax({
url: wikiAPI,
dataType: "json",
success: displayResults
});
现在,当ajax请求成功时,jquery将调用您提供的函数。
您可以阅读documentation函数中期望的参数:
success
Type: Function( Anything data, String textStatus, jqXHR jqXHR )
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
因此,您的 displayResults
函数将接收三个参数:data
(可以是任何类型)、textStatus
(字符串)和 jqXHR
(XMLHttpRequest 对象)。尽管参数名称可以是您想要的任何名称,但通常的做法是使其与文档保持一致。
关于javascript - Ajax json 请求和响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44081968/