ajax怎么接收json数据

使用ajax接收json数据的步骤如下:

创建一个XMLHttpRequest对象:

var xhr = new XMLHttpRequest();

设置请求的方法和URL:

xhr.open("GET", "example.json", true);  // 使用GET方法请求example.json文件

设置响应的数据类型为json:

xhr.responseType = "json";

监听onload事件,当请求成功完成时调用回调函数:

xhr.onload = function() {
  if (xhr.status === 200) {
    var jsonResponse = xhr.response;
    // 在这里处理接收到的json数据
  }
};

发送请求:

xhr.send();

完整的例子如下所示:

var xhr = new XMLHttpRequest();
xhr.open("GET", "example.json", true);
xhr.responseType = "json";
xhr.onload = function() {
  if (xhr.status === 200) {
    var jsonResponse = xhr.response;
    // 在这里处理接收到的json数据
  }
};
xhr.send();

在上面的例子中,example.json是一个包含json数据的文件的URL。当请求成功完成后,可以通过xhr.response获取到接收到的json数据。根据实际需求,可以在xhr.onload回调函数中对数据进行处理。

阅读剩余
THE END