2017-05-16 24 views
0

這是我在這裏的第一篇文章,我希望我不會違反任何規則。如果我這樣做,請打電話給我失敗,以便我可以再次學習。爲什麼我的AJAX代碼將API中的信息無法使用?

因此,我寫了一個代碼,應該將來自API的信息作爲文本呈現在我的html頁面上。 Ajax代碼不工作,我不知道爲什麼,什麼也不顯示在控制檯上,而我只得到了由鉻這樣的警告:

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/ .

這裏是我的AJAX代碼:難道我做錯了什麼?

$.ajax 
({ 
    type: "GET", 
    url: "xxxxxxxxxx", 
    dataType: 'json', 
    async: false, 
    username: "xxxxxxx", 
    password: "xxxxxxxxxx", 
    data: '{ "id" }', 
    success: function(){ 
    alert('Thanks for your comment!'); 
    } 
}); 
+0

Warning is co因爲ajax異步標誌是錯誤的。這意味着它是對數據庫的同步調用。你可以檢查鉻網絡中的響應標籤嗎? – RahulB

+0

嘗試添加「error」回調函數,如: 'error:function(){ alert('error!'); }' – Alessandro

+0

感謝您的回答。我將async更改爲True,並且警告不再顯示,但是我的sucess功能仍然不起作用,這意味着api未加載。請注意,當我使用相同的代碼用於另一個未使用密碼和用戶名保護的API時,代碼完美地工作,我做錯了什麼? –

回答

0

遵守以下代碼段應該幫助你,我建議堅持使用

$.ajax({...}) 
//Code to run if the request succeeds (is done); 
//The response is passed to the function 
.done(callback(json)) 
//Code to run if the request fails; the raw request and 
//status codes are passed to the function 
.fail(callback(xhr, status, errorThrown)) 
//Code to run regardless of success or failure; 
.always(callback(xhr, status)) 

方法上ajax

$(document).ready(function() { 
 

 
    $("#btn").click(function(event) { 
 
    var content = $("#content"); 
 
    var url = $("#url").val(); 
 

 

 

 
    $.ajax({ 
 
     type: "GET", 
 
     url: url, 
 
     data:{id:3},//observe this line, send object instead 
 
     dataType: 'json', 
 
     async: false 
 
    }) 
 
    .done(function(data){ 
 
     alert('Thanks for your comment!'); 
 
     content.text(JSON.stringify(data));//convert object to string 
 
    }) 
 
    .fail() 
 
    .always(); 
 

 
    }); 
 

 

 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<!-- Latest compiled and minified CSS --> 
 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 
 

 
<p> 
 
    Enter the url to fetch on the div using jquery ajax method 
 
    <input id="url" class="" placeholder="Enter url" value="https://jsonplaceholder.typicode.com/posts" /> 
 
    <button class="btn btn-primary" id="btn">Fetch</button> 
 
</p> 
 

 
<br> 
 

 
<div id="content" class="container well"> 
 
    content is going to show here 
 
</div>
從jQuery的文檔解釋

+0

嗨,謝謝你的回答。該代碼與普通的API一起工作,但是需要自動化的API,它不起作用。我如何解決它? –

+0

它是一個基於令牌的身份驗證或哪種類型的身份驗證方法 –

+0

嗯,我不完全確定,但是當我在瀏覽器中發佈網址時,我來到登錄頁面(用戶名和密碼),我必須把用戶名和密碼將重定向到API –

相關問題