kyo*_*kyo 4 javascript ajax rest jquery json
我想知道进行 AJAX 调用的最佳方法是什么。
这就是我现在所拥有的,并且效果很好。
$.ajax({
url: "/rest/computer",
type: "GET",
dataType: "json",
data: {
assessmentId: "123",
classroomId: "234"
},
success: function(objects) {
// .... code ....
}
});
Run Code Online (Sandbox Code Playgroud)
我目前正在寻找另一种进行 Ajax 调用的方法。如果有,我应该使用我的方法吗?
我应该将 Ajax 调用移动到它自己的函数中并回调它吗?
对此的任何建议将不胜感激。
是的,还有其他一些方法可以调用 ajax
jQuery
var get_data = function(){
var result = false;
$.get('/rest/computer').done(function(awesome_data){
result = awesome_data;
});
return result;
}
Run Code Online (Sandbox Code Playgroud)
$.getJSON
$.getJSON( '/rest/computer', { assessmentId:"123", classroomId:"234"})
.done( function(resp){
// handle response here
}).fail(function(){
alert('Oooops');
});
Run Code Online (Sandbox Code Playgroud)
如果您没有在代码中使用 jQuery,则此答案适合您
你的代码应该是这样的:
function foo() {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "/rest/computer");
httpRequest.send();
return httpRequest.responseText;
}
var result = foo(); // always ends up being 'undefined'
Run Code Online (Sandbox Code Playgroud)
还有所有现代浏览器都支持的异步 API
fetch('./api/projects',
{
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'Beispielprojekt',
url: 'http://www.example.com',
})
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.error(error);
});Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23279 次 |
| 最近记录: |