【问题标题】:Why is my AJax code for bringing information from an API not working?为什么我的用于从 API 获取信息的 AJax 代码不起作用?
【发布时间】:2017-05-16 19:37:34
【问题描述】:

这是我在这里的第一篇文章,我希望我不会违反任何规则。如果我这样做了,请把我的失败告诉我,以便我下次学习。

所以我编写了一个代码,该代码应该将来自 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 异步标志为假。这意味着它是对 DB 的同步调用。您可以查看 chrome 网络中的响应选项卡吗?
  • 尝试添加“错误”回调函数,如:,error: function(){ alert('error!'); }
  • 感谢您的回答。我将 async 更改为 True 并且警告不再显示,但我的 sucess 功能仍然不起作用,这意味着未加载 api。请注意,当我对另一个不受密码和用户名保护的 API 使用相同的代码时,代码运行良好,我做错了什么?
  • 我添加了错误功能,接下来呢?

标签: javascript ajax asp.net-web-api


【解决方案1】:

观察下面的代码 sn-p 它应该可以帮助你,我建议坚持使用

$.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)) 

解释的方法 来自 jquery doc 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>

【讨论】:

  • 您好,感谢您的回答。该代码适用于普通 API,但需要授权的 API 不起作用。我该如何解决?
  • 是基于令牌的身份验证还是哪种类型的身份验证方法
  • 嗯,我不太确定,但是当我在浏览器中发布 url 时,我来到了一个登录页面(用户名和密码),我必须输入用户名和密码才能重定向到API
  • 如果您可以帮助使用示例 api 进行测试,我不太明白您的意思。您想说的是,当您尝试访问 api 时,您将被重定向以输入用户名和密码,然后如果成功则转到您最初请求的 api 对吗?
  • 是的,没错,这里是 API,如果你可以尝试打开 url 看看你得到了什么:nfcgl.etterlid.org/api/handins/3
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-23
  • 2014-01-23
  • 2013-08-06
  • 2021-10-29
  • 1970-01-01
相关资源
最近更新 更多