簡體   English   中英

如何使用jquery的$ ajax調用進行REST調用?

[英]How to make a REST call using jquery's $ajax call?

我正在使用關於這個問題的答案。 結果,我的html頁面如下所示:

<!DOCTYPE html>
<html>
<head>
    <script src="path\jquery-2.1.1"></script>
    <script>
        function myFunction() {
            alert('Clicked!');
            $.ajax({
                url: "http://localhost:51399/api/webapi",
                type: 'GET',
                success: function (data) {
                    alert(data.error);
                    $('#demo').html(data);
                },
                error: function (data) {
                    alert(data);
                }
            });
        }
    </script>
</head>
<body>

    <p>Click the button to trigger a function.</p>

    <button onclick="myFunction()">Click me</button>

    <p id="demo"></p>
</body>
</html>

當我單擊按鈕時,什么也沒有發生。 我不確定是否進行過ajax調用,或者回調是否成功。 我缺少什么,如何解決它,以便GET REST調用轉到我指定的URL?

PS:我是javascript和jquery的初學者。

也許嘗試:

$.ajax({
  url: "http://blockchain.info/latestblock",
  type: 'GET',
  success: function(data) {
            $('#demo').html(data);
  },
  error: function(jqXHR, textStatus, errorThrown) {
                console.log("error: " + errorThrown + " || status: " + textStatus + " || data: " + jqXHR);
        }
});

或(更現代的方式):

function myFunction(){
  $.ajax({
    url: "http://blockchain.info/latestblock",
    type: 'GET'
  });
}

function handleData(data) {
  $('#demo').html(data);
}

function handleError(jqXHR, textStatus, errorThrown) {
                console.log("error: " + errorThrown + " || status: " + textStatus + " || data: " + jqXHR);
}

myFunction().fail(handleError)
myFunction().done(handleData);

沃爾德的上述回答是完全有效的。 但是,我的代碼存在的問題是我試圖使用其絕對路徑引用jquery.js文件,但該文件的絕對路徑被禁止。 一旦我將路徑設為相對路徑(並添加了擴展名……讓我很愚蠢),電話就通過了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM