.ajax()和.getJSON()之间的区别是什么

时间:2016-02-17 04:00:22

标签: json ajax

我想了解这两者之间的区别是什么?我已经读过.getJSON调用.ajax。但功能上有什么不同?哪个会起作用?

想象一下,您正在尝试编写一个客户端Web应用程序,该Web应用程序与代表在线汽车目录的以下RESTFUL API交互: GET / cars - 返回目录中所有汽车的列表

Example response:
{"cars": [
    {"id": 1, "model": "Alice in Wonderland", "make": "Chevy"},
    {"id": 2, "model": "Civic", "make": "Honda"}
]}

POST /cars - Creates a new car based on the given info 

Example request:
{"model": "Wrangler", "make": "Jeep"} 

Example response:
{"id": 3} 

GET /cars/<id> - Returns info about the car with that id 

Example response:
{"id": 1, "model": "Alice in Wonderland", "make": "Chevy"} 

PUT /cars/<id> - Overrides info about the car with the given id with the new data 

Example request:
{"model": "Wrangler", "make": "Jeep"} 

DELETE /cars/<id> - Deletes the car at the given id. The id may be recycled for other cars 

您已被指示编写一些代码:

  1. 删除Chevy制造的所有汽车
  2. 将Jeep写入的所有汽车的模型修改为全部大写

    $.ajax({ url: "/cars", type: "GET" }, function(data) {
            data.cars.forEach(function (car) {
                var endpoint = "/car/" + car.id;
                if (car.make == "Chevy") {
                    $.ajax({ url: endpoint, type: "DELETE" });
                } else if (car.make == "Toyota") {
                    var request = {title: car.title.toUpperCase(), make: car.make};
                    $.ajax({ url: endpoint, type: "PUT", data: JSON.stringify(request) });
                }
            });
        });
    
    $.getJSON("/cars", function(data) {
        data.cars.forEach(function (car) {
            var endpoint = "/car/" + car.id;
            if (car.make == "Chevy") {
                $.ajax({ url: endpoint, type: "DELETE" });
            } else if (car.make == "Toyota") {
                var request = {title: car.title.toUpperCase(), make: car.make};
                $.ajax({
                    url: endpoint,
                    type: "PUT",
                    data: JSON.stringify(request),
                    contentType: "application.json"
                });
            }
        });
    });
    

0 个答案:

没有答案