代码之家  ›  专栏  ›  技术社区  ›  Jimmy

Ajax调用不会将JSON返回到网站正文中

  •  0
  • Jimmy  · 技术社区  · 7 年前

    我试图从Ajax调用中返回一些JSON,并将其放入HTML体中,但我正在努力处理下面的代码。有人能告诉我哪里出错了吗?

    $("button").click(function() {
      $.ajax({
        url: 'http://jsonplaceholder.typicode.com/todos/1',
        type: "POST",
        dataType: 'json',
        data: ({
          type: 'main'
        }),
        success: function(result) {
          $("#result").html(result);
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <button id='buttonJSONP'>Echo JSONP</button>
    <div id='result'></div>
    3 回复  |  直到 7 年前
        1
  •  1
  •   Get Off My Lawn    7 年前

    您需要使用 get ,否则您需要查看您的API post 请求。

    如果是 邮递 ,数据看起来不像这样 ({}) . 去掉括号,只用大括号 {} .

    使用A 得到 你需要移动你的 data 对象也进入URL,因为 得到 请求没有正文。

    $("button").click(function() {
      $.ajax({
        url: 'http://jsonplaceholder.typicode.com/todos/1?type=main',
        type: "GET",
        dataType: 'json',
        success: function(result) {
          $("#result").html(Object.values(result).join(','));
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <button id='buttonJSONP'>Echo JSONP</button>
    <div id='result'></div>
        2
  •  0
  •   Niladri    7 年前

    您的代码中有一些问题-

    1. 由于这是一个POST请求,您需要更改输入,如下所示,同时删除 ( )

      data: { "type": "main" }

    2. 对于POST请求,API URL也不正确,即使输入正确,也会得到404错误。发布的正确URL如下-

    url: 'http://jsonplaceholder.typicode.com/todos/'

    参考文献: Fake JSON api documentation

    所以您的完整代码应该如下所示-

    $("button").click(function() {
      $.ajax({
        url: 'http://jsonplaceholder.typicode.com/todos/',
        type: "POST",
        dataType: 'json',
        data:{
          "type": "main"
        },
        success: function(result) {
          $("#result").html(Object.values(result).join("-"));
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <button id='buttonJSONP'>Echo JSONP</button>
    <div id='result'></div>

    响应状态将为HTTP 201。

        3
  •  0
  •   boudlal    7 年前

    在上面的示例中,您尝试将数据发布到get url中。

    如果您想从这个URL返回JSON响应,您必须使用GET而不是POST,您的代码应该如下所示:

    $("button").click(function() {
      $.ajax({
        url: 'http://jsonplaceholder.typicode.com/todos/1',
        success: function(result) {
          console.log(result);
          $("#result").html(result.key);
        }
      });
    });