ajax从Web API获取json但返回错误

时间:2017-03-15 02:52:48

标签: ajax api

我使用ajax从Web API获取json,如下所示。

浏览器日志显示提取了json结果,但页面返回了错误函数:alert("请稍后再试")。 browser log image 有什么不对吗?

谢谢!

$.ajax({  
   url :"http://dgidb.genome.wustl.edu/api/v1/interactions.json", 
   type:"get",  
   async:false,  
   data: {genes: genes, interaction_sources: interaction_sources},
   dataType:"jsonp",
   jsonp:"callback",
   jsonpCallback:"message",
   success: function(data){  
      alert(data);
   },
   error: function(){  
      alert("Please try later");
   } 
}); 

3 个答案:

答案 0 :(得分:0)

删除dataType:" jsonp"或使用dataType:" json"

答案 1 :(得分:0)

使用你的代码我无法让它工作,除非我在“基因”和“interaction_sources”周围加上引号。

如果我直接访问网址:http://dgidb.genome.wustl.edu/api/v1/interactions.json,则会显示: {“错误”:“您必须输入至少一个基因名称才能搜索!”}

也许你应该使用搜索参数而不是“基因”和“interaction_sources”?

编辑:如果您可以为您尝试访问的json提供API,我们可以调试它吗?

$("#runme").on("click", function() {
  RunMe();
});

function RunMe() {
  $.ajax({
    url: "http://dgidb.genome.wustl.edu/api/v1/interactions.json",
    type: "get",
    async: false,
    data: {
      genes: "genes",
      interaction_sources: "interaction_sources"
    },
    dataType: "jsonp",
    jsonp: "callback",
    jsonpCallback: "message",
    success: function(data) {
      alert(data);
    },
    error: function() {
      alert("Please try later");
    }
  });

};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<button id="runme">RUN ME!!!</button>

答案 2 :(得分:0)

确保API响应日期为 application / json 标题

{
  "matchedTerms": [],
  "unmatchedTerms": [
    {
      "searchTerm": "GENES",
      "suggestions": []
    }
  ]
}

此响应的Content-Type为application / json。我试过这是在手动POSTMAP,它工作。只需修复Content-Type标头值。