使用AJAX搜索API

时间:2016-11-30 21:55:49

标签: javascript jquery

我正在尝试创建一个允许用户搜索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();
}

1 个答案:

答案 0 :(得分: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));
    }
});

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