如何使用jQuery $.ajax获取json文件

How to get a json file with jQuery $.ajax?

本文关键字:获取 json 文件 ajax 何使用 jQuery      更新时间:2023-09-26

我正在做一些大学考试测试,要求我从对象中的href的url获取JSON文件。在此之后,我需要用JSON文件上的信息动态更改html,所以我想我需要使用$.ajax()或$.get()方法。

我在堆栈溢出上发现了几个代码,但似乎没有什么对我有用,我可以让我的代码只使用$.load()方法工作,而其他方法什么也不做,还有. addclass (), . removeclass()和event.preventDefault()工作得很好。

下面是我的代码:
    $(document).ready(function()
    {
     $("nav li a").click(function(event)
     {
      $("nav li a").not(this).removeClass("active");
      $(this).addClass("active");

      $("#ris").load($(this).attr('href')); //this work
      $.ajax({url: $(this).attr('href'), dataType: "json",  //this give the alert
       success: function(result)
        {$("#ris").html(result);},
       error: function(){alert("Error");}
      });
      $.get($(this).attr('href'), function(json) { //this doesn't work
          $("#ris").html(json);
      });
      $.getJSON($(this).attr('href'), function(json){ //this doesn't work
        $("#ris").html(json);});
      event.preventDefault();
    });
  });

html:我只把nav项放在这里,#ris在页面的末尾

  <nav>
    <li><a href="./Asia.json">Asia</a></li>
    <li><a href="./Europa.json">Europa</a></li>
    <li><a href="./America.json">America</a></li>
    <li><a href="./Africa.json">Africa</a></li>
  </nav>

现在我只是把结果放在#ris中看看它是否有效。但是我不明白为什么我不能对任何方法进行有效的get调用。

编辑:服务器永远不会收到JSON文件的GET请求。(服务器日志)

您应该发布一个类似api的数据并读取如下响应;

$.post("your_json_response_address", {"you_can_post":"anything"}, function(data){
    console.log(data);
    $("#ris").html(data);
    //code what you want...
})