如何使用 React 在客户端向外部站点发出 AJAX GET 请求
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
您应该查看这些关于跨域请求的答案。
jQuery AJAX cross domain
Loading cross domain endpoint with jQuery AJAX
它可能会引导您找到正确答案。
当您尝试从其他域获取 json
时,存在安全问题,因此默认行为不允许这样做,但您可以使用 jsonp
作为解决方法。
以下是包含 jsonp
的 GET 请求的修改版本。添加指定 jsonp
return 类型和回调函数名称。
// 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);
}
});
你好,我是 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
您应该查看这些关于跨域请求的答案。
jQuery AJAX cross domain
Loading cross domain endpoint with jQuery AJAX
它可能会引导您找到正确答案。
当您尝试从其他域获取 json
时,存在安全问题,因此默认行为不允许这样做,但您可以使用 jsonp
作为解决方法。
以下是包含 jsonp
的 GET 请求的修改版本。添加指定 jsonp
return 类型和回调函数名称。
// 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);
}
});