javascript - 使用 AJAX 搜索 API

标签 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();
}

最佳答案

有一个 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));
    }
});

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

关于javascript - 使用 AJAX 搜索 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40898946/

相关文章:

jquery - 将回调完成函数添加到 jQuery Final Countdown 的多个实例

jquery - 验证 jQuery 包装集中是否存在文本

Jquery 无法与 Recaptcha 一起使用

javascript - 如何替换 CasperJS 弹出窗口中的导航器对象?

javascript - 请参阅 Meteor.js 中允许/拒绝规则的更新文档

javascript - JavaScript 关联数组的长度

javascript - 弹出框同时打开

javascript - 在其 js 容器中垂直居中文本 - progressbar.js

javascript - 当我们选中和取消选中其他表中的复选框时,如何在 jquery 中的表中添加/删除行?

javascript - 在 tinymce 窗口上触发 keyup 事件