[英]Why is my AJax code for bringing information from an API not working?
这是我在这里的第一篇文章,我希望我不会违反任何规则。 如果我这样做,请给我打电话失败,以便我下次学习。
因此,我编写了一个代码,该代码应将来自API的信息作为文本呈现在html页面上。 AJAX代码无法正常工作,我不知道为什么,控制台上什么也没显示,我从chrome中仅收到此警告:
[弃用]不赞成在主线程上使用同步XMLHttpRequest,因为它对最终用户的体验具有不利影响。 如需更多帮助,请访问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!');
}
});
观察下面的代码片段,它应该可以为您提供帮助,我建议您坚持使用
$.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上的 jQuery文档中解释的方法
$(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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.