📜  jQuery getJSON()方法

📅  最后修改于: 2020-11-27 01:17:16             🧑  作者: Mango

jQuery getJSON()方法

此jQuery方法用于使用AJAX HTTP GET请求从服务器获取JSON数据。

句法

$(selector).getJSON(URL, data, success(data, status, xhr))

参数值

此方法包括三个参数值,其中一个是必需的,其他是可选的。我们必须将URL参数包含在getJSON()方法中。下表定义了getJSON()方法的参数值。

Parameter Values
URL It is the URL to which the request is sent. It is a mandatory parameter.
data It is an optional parameter. It is the data sent to the server.
success(data, status, xhr) This is also an optional parameter. It is a callback function that executes on the successful server request.
It also has three parameters that are data, status, and xhr in which data contains the data returned from the server, status represents the request status like “success”, “error”, etc., and the xhr contains the XMLHttpRequest object.

现在,让我们看一个使用getJSON()方法的简单示例。

在此示例中,我们使用getJSON()方法从外部JSON文件中获取JSON数据。这里,有一个名为sample.json的外部JSON文件,其中包含学生的详细信息。

我们正在使用getJSON()方法的两个参数,即URL和callback函数。

URL参数设置为值sample.JSON。我们使用回调函数的两个参数,分别是data和status,其中第一个参数保存请求页面的数据,第二个参数保存请求状态。在输出中,我们可以看到从服务器加载的数据,并且请求的状态为成功。

我们必须单击给定的按钮以从外部JSON文件中获取数据。

sample.json

{
"name" : "John",
"age" : "23",
"rollno" : "11",
"standard" : "Post-Graduate"
}

Example2.html




 jQuery getJSON() method 






Welcome to the javaTpoint.com

It is an example of using the jQuery getJson() method

Click the following button to fetch the data.

输出量

执行完上述代码后,输出将为-

点击给定的按钮后,将显示一个对话框,其中包含如下所示的数据-

关闭对话框后,学生的数据将显示在页面上,如以下屏幕截图所示。在下面的屏幕截图中,我们可以看到请求的状态为成功。