进行Ajax调用的另一种方法是什么?

时间:2015-07-17 17:59:24

标签: javascript jquery ajax json rest

我想知道进行AJAX调用的最佳方法是什么。

这就是我现在所拥有的,它运作得很好。

$.ajax({

    url: "/rest/computer",
    type: "GET",
    dataType: "json",

    data: {
        assessmentId: "123",
        classroomId:  "234"
    },

    success: function(objects) {


    // .... code ....


    }
});

我目前正在寻找另一种进行Ajax调用的方法。 如果有,我应该使用我的方法吗?

我应该将Ajax调用移入自己的函数并将其调回吗?

对此有任何建议将不胜感激。

4 个答案:

答案 0 :(得分:4)

是的还有一些其他方法可以调用ajax

<强>的jQuery

var get_data = function(){
    var result = false;
    $.get('/rest/computer').done(function(awesome_data){
        result = awesome_data;
    });

    return result;
}

<强> $。的getJSON

$.getJSON( '/rest/computer', { assessmentId:"123", classroomId:"234"})
  .done( function(resp){
    // handle response here
}).fail(function(){
   alert('Oooops');
});

如果您未在代码中使用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'

答案 1 :(得分:1)

不清楚问题的基本背景是什么,但例如显示您可以使用:

$.getJSON( url, { assessmentId:"123", classroomId:"234"})
  .done( function(resp){
    // handle response here
}).fail(function(){
   alert('Oooops');
});

$ .getJSON是$.ajax的包装器,简化了需要添加许多已经预设的选项

答案 2 :(得分:1)

以下还有一个使用post方法调用的ajax类型。

var assessmentId = "123"
var formURL = '/rest/computer';
var postData = { "action":"add","data":assessmentId};
$.post(formURL, postData, function( response ) {
    // handle response here 
});

答案 3 :(得分:1)

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