【问题标题】:How to make AJAX GET request on the client to external site with React如何使用 React 在客户端向外部站点发出 AJAX GET 请求
【发布时间】:2015-07-13 15:54:24
【问题描述】:

您好,我是 React 新手,我正在尝试向外部 API 发出 AJAX GET 请求。但是,我添加的 URL 是在我的主机前面添加的。如果我正在做某事,请告诉我。下面是我的代码。

$.ajax({
  type: 'GET',
  url: 'http://www.someapi.com/?i='+someId,
  async: false,
  dataType: 'json',
  success: function(data) {
    this.setState({data: data});
  }.bind(this),
  error: function(e) {
     console.log('error', e);
  }
});

GET 请求正在发送到localhost:3000/http://www.someapi.com/?i=1

【问题讨论】:

  • 永远不要使用async: false
  • 因为它在请求加载时冻结了浏览器/选项卡。如果你要做网络前端,你真的需要学会正确使用异步回调。
  • 我不希望用户在加载数据之前做任何其他事情。对于这种情况,应该没问题吧?
  • 没有。普遍都不好。如果您不希望用户在加载数据之前执行任何操作,请在加载之前隐藏或禁用相关 UI。

标签: javascript jquery ajax get reactjs


【解决方案1】:

当您尝试从其他域获取 json 时,存在安全问题,因此默认行为不允许这样做,但您可以使用 jsonp 作为解决方法。

以下是包含jsonp 的 GET 请求的修改版本。添加指定jsonp 返回类型和回调函数名称。

    // If you are doing making this request multiple times the AJAX request
    // may fail due to the same callback name, so you could generate random    
    // callback names to get around it.
    var callback = 'c'+Math.floor((Math.random()*100000000)+1);

    $.ajax({
      type: 'GET',
      url: 'http://www.someapi.com/?i='+id,
      jsonpCallback: callback, //specify callback name
      contentType: 'application/json',
      dataType: 'jsonp', //specify jsonp
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(e) {
         console.log('error', e);
      }
    });

【讨论】:

  • 很高兴我能帮上忙!还可以将CORS 视为更安全的方式。
【解决方案2】:

你应该看看这些关于跨域请求的答案。

jQuery AJAX cross domain

Loading cross domain endpoint with jQuery AJAX

它可能会引导你找到正确的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-18
    • 2019-01-13
    • 2012-12-10
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多