Javascript 当I';我正在使用jquery
我正在尝试从此页面获取json 但它返回一个错误Javascript 当I';我正在使用jquery,javascript,php,jquery,json,Javascript,Php,Jquery,Json,我正在尝试从此页面获取json 但它返回一个错误 XMLHttpRequest cannot load http://www.designerbh.com/js.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 有人能帮我吗 function AJAX_JSON_Req( url )
XMLHttpRequest cannot load http://www.designerbh.com/js.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
有人能帮我吗
function AJAX_JSON_Req( url )
{
var AJAX_req = new XMLHttpRequest();
AJAX_req.open( "GET", url, true );
AJAX_req.setRequestHeader("Content-type", "application/json");
AJAX_req.onreadystatechange = function()
{
if( AJAX_req.readyState == 4 && AJAX_req.status == 200 )
{
var response = JSON.parse( AJAX_req.responseText );
document.write( response.name );
}
}
AJAX_req.send();
}
AJAX_JSON_Req( 'http://www.designerbh.com/js.php' );
在您的例子中,您使用的是跨站点ajax,因此您可以使用jsonp来完成这样的任务 您可以使用jquery来实现这一点
$.ajax({
url: 'http://.....',
dataType: 'jsonp',
success: function(response){
}
})
如果您的浏览器支持跨源资源共享,但响应的服务器不允许您的域,则您将收到此类警告。由于您正在尝试解析JSON,一种解决方法是使用Ajax加载内容,而不是
XMLHttpRequest
示例
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <!-- Loads jQuery 1.11.0 -->
</head>
<html>
<body>
<script>
function getData() {
$.ajax({
url : 'http://www.designerbh.com/js.php', //This is the URL we will be calling to gather the data from
type: 'GET', //This is the type of our request
dataType: "json", //switch to JSONP for JSONP
success : callback, //Call callback() function when the request is complete to process the gathered data
data: {
//GET parameters should be specified here
//Example
//parameter1: "value1",
//parameter2: "value2"
}
})
}
function callback(data) {
//Since that http://www.designerbh.com/js.php gives out {"text":"omrele"}, we can access the text variable by calling data.text
alert(data.text); //omrele
}
getData(); //call the getData() function to start sending the GET request
</script>
</body>
</html>
函数getData(){
$.ajax({
网址:'http://www.designerbh.com/js.php“,//这是我们将调用以从中收集数据的URL
类型:'GET',//这是我们请求的类型
数据类型:“json”,//切换到JSONP以获得JSONP
success:callback,//请求完成时调用callback()函数来处理收集的数据
数据:{
//应在此处指定GET参数
//范例
//参数1:“值1”,
//参数2:“值2”
}
})
}
函数回调(数据){
//从那以后http://www.designerbh.com/js.php 给出{“text”:“omrele”},我们可以通过调用data.text来访问text变量
警报(data.text);//omrele
}
getData()//调用getData()函数开始发送GET请求
如果没有明确允许,您无法通过ajax从随机网站获取内容。我如何修复它?你知道吗?猜猜看:如果你在Google中键入“Access Control Allow Origin”,第一页会显示详细解释问题的结果。这是浏览器固有的安全功能。除了创建一个服务器端代理服务来为您获取内容之外,您无法通过任何方式“修复”它。它对我很有效,非常感谢您,我尝试了很多脚本,我在php中设置了allow标头,并使用了很多代码