Javascript 使用AJAX搜索API

Javascript 使用AJAX搜索API,javascript,jquery,Javascript,Jquery,我正在尝试制作一个应用程序,允许用户通过College Scorecard API进行搜索。我对ajax非常陌生,所以我不确定我在这里做了哪些错误的事情。我将textAjax()函数挂接到HTML表单上的一个按钮上,但当我运行代码时,请求失败。这是我的密码 function testAjax(){ $.ajax({ type : 'POST', url : 'https://api.data.gov/ed/collegescorecard/v1/schools?school.na

我正在尝试制作一个应用程序,允许用户通过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();
}
函数testAjax(){
$.ajax({
键入:“POST”,
网址:'https://api.data.gov/ed/collegescorecard/v1/schools?school.name=University%20of%20Cincinnati&api_key=',
数据类型:“json”,
成功:功能(数据){
//如果请求成功,请处理数据
警报(数据);
},
错误:函数(请求){
//如果请求失败,记录发生的情况
警报(JSON.stringify(“错误:+请求”);
}
});
}
函数按钮单击(){
var url=testAjax();
}

有一个
数据
属性,用于将查询添加到您的url,这样您就不必自己进行查询。看看这个:

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));
    }
});

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

请求如何失败?网络错误?如果是这样,请与我们分享API的回复。您是否在执行
POST
时应该执行
GET
?-它看起来应该是一个
GET
(作为一个搜索和所有)哇,太漂亮了,它会自动添加到url的末尾。谢谢你的建议!