【问题标题】:Searching an API using AJAX使用 AJAX 搜索 API
【发布时间】:2016-12-01 06:00:57
【问题描述】:

我正在尝试制作一个允许用户通过 College Scorecard API 进行搜索的应用程序。我对 ajax 很陌生,所以我不确定我在这里做错了什么。我将 textAjax() 函数连接到我的 HTML 表单上的一个按钮,但是当我运行我的代码时,请求失败。这是我的代码。

function testAjax(){
$.ajax({
    type : 'POST',
    url : 'https://api.data.gov/ed/collegescorecard/v1/schools?school.name=University%20of%20Cincinnati&api_key=<API-KEY>',
    dataType : 'json',
    success : function(data) {
        //if the request is successful do something with the data
        alert(data);
    },
    error : function(request){
        //if the request fails, log what happened
        alert(JSON.stringify("Error: " + request));
    }
});

}

function buttonClick() {
    var url = testAjax();
}

【问题讨论】:

  • 请求如何失败?网络错误?如果是这样,请与我们分享来自 API 的响应
  • 你在做POST,而你应该做GET? - 看起来应该是GET(作为搜索和所有)

标签: javascript jquery


【解决方案1】:

有一个data 属性用于将查询添加到您的网址,因此您不必自己做。看看这个:

function testAjax(){
$.ajax({
    type : 'POST',
    url : 'https://api.data.gov/ed/collegescorecard/v1/schools',
    data: {
       'name': 'University of Cincinnati',
       'api_key': 'whatever'
    },
    dataType : 'json',
    success : function(data) {
        //if the request is successful do something with the data
        alert(data);
    },
    error : function(request){
        //if the request fails, log what happened
        alert(JSON.stringify("Error: " + request));
    }
});

我不确定这是否是您唯一的问题,但它可能会有所帮助。

【讨论】:

  • 哇,太漂亮了,它会自动添加到网址的末尾。感谢您的建议!
猜你喜欢
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多