我正在尝试制作一个应用程序,允许用户通过 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/