![](/img/trans.png)
[英]How to get an Ajax request from an external server using client side JavaScript
[英]How to make AJAX GET request on the client to external site with React
您好我是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
当您尝试从不同的域获取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);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.