【问题标题】:JSON returns an error when I'm using jquery [closed]当我使用 jquery 时,JSON 返回错误 [关闭]
【发布时间】:2014-08-16 01:08:05
【问题描述】:

我正在尝试从此页面获取 json

http://www.designerbh.com/js.php

但它返回一个错误。

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 从随机网站获取内容。
  • 我该如何解决?你知道吗?
  • 猜猜看:如果您在 Google 中输入“Access-Control-Allow-Origin”,第一页就会显示详细解释问题的结果。
  • 这是一个固有的浏览器安全功能。除了创建服务器端代理服务来为您获取内容之外,您无法通过任何方式“修复”它。

标签: javascript php jquery json


【解决方案1】:

如果您的浏览器支持跨域资源共享,但响应服务器不允许您的域,您将收到此类警告。由于您正在尝试解析 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>

【讨论】:

  • 它对我来说很好,非常感谢你我尝试了很多脚本我在头文件 php 中设置了允许并使用这个代码坦克你这么多
【解决方案2】:

在您的情况下,您使用的是跨站点 ajax,因此您可以将 jsonp 用于此类任务

你可以使用 jquery 来做这个

$.ajax({
url: 'http://.....',
dataType: 'jsonp',
success: function(response){

}
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多