【问题标题】:jquery crossdomain ajax and getJason return errorjquery跨域ajax和getJson返回错误
【发布时间】:2013-11-23 12:11:53
【问题描述】:

您好,我正在尝试按照以下说明使用 jQuery 进行 ajax 调用:http://data.hud.gov/housing_counseling.html

但是由于这是一个跨域请求,所以我需要做jsonp(对此不了解)

经过研究,我以两种方式完成了调用,但我不断收到错误消息,数据位于浏览器中的某个位置,但我不知道如何访问它。

注意 url 上的回调参数(如果我不包含它,我会得到 Origin is not allowed by Access-Control-Allow-Origin。)

第一次通话:

function loadJson() 
    {
        var statesurl = "http://data.hud.gov/Housing_Counselor/search?AgencyName=&City=&State=CA&jsoncallback=?"
        $.getJSON(statesurl, null, function(result){


        }).done(function(result) {

            var items = [];
            $.each( result, function( key, val ) {
                items.push( "<li id='" + key + "'>" + val + "</li>" );
                console.log(key + ": " + val)
            });

            $( "<ul/>", {
                "class": "my-new-list",
                html: items.join( "" )
            }).appendTo( "div#thestates" ); 

        }).fail(function() {
            console.log( "error" );
        })
    }

$( "#loadstates" ).click(function() { loadJson()});

我为 callback 参数获得了一个随机回调名称,例如 http://data.hud.gov/Housing_Counselor/search?AgencyName=&City=&State=CA&jsoncallback=jQuery19107074434771202505_1384407999935&_=1384407999936 通过 Chrome 的控制台,我可以看到响应是带有键值对的 JSON 数据。

如果我尝试使用 $.ajax 调用,$.ajax 调用也会发生同样的情况:

function loadJsonP() 
{
    var statesurl = "http://data.hud.gov/Housing_Counselor/search?AgencyName=&City=&State=CA&jsoncallback=?"
    $.ajax({
        url:statesurl,
        dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
        success:function(json){
             // do stuff with json (in this case an array)
             console.log(json_encode(json))
        },
        error:function(){
            console.log("Error");
        },
    });
}

我得到了与上图类似的响应。虽然 console.log 的输出都是“错误”,但我看到了 200 响应

我应该如何处理响应以获得成功的响应并操作 JSON 数据,这显然是在浏览器的某个地方

谢谢

【问题讨论】:

    标签: jquery cross-domain jsonp


    【解决方案1】:

    更新答案

    我遇到的问题是由我的浏览器的限制引起的(我知道,但要制定我的答案,我觉得我必须澄清这个事实),它阻止了通过 ajax 从另一个域加载内容(即跨域请求)。

    有关跨域 ajax 限制的简单易懂的解释,您可以阅读这篇出色的文章:https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&redirectslug=HTTP_access_control#Access-Control-Expose-Header

    我以为我正在获取数据,但我认为它在我的浏览器中的某个地方。我没有获取数据,我看到的是从响应服务器重定向的网页内容。如果我没有清楚地解释这一点,没关系,继续前进。

    为了完成这项工作,我必须使用 3 个文件,触发 ajax 调用的 html 文件,我有脚本的 js 文件,以及 (VIP) 发出请求并格式化请求以满足的文件$.ajax() 规范(我正在使用 PHP)

    javascript 文件:

    $( document ).ready(function() {
    
        if (!(window.jQuery)) {  
            console.log('JQUERY NOT LOADED');
        }
    
        function loadJsonP(parametrizedurl) 
        {
    
            $.ajax({
                type: 'GET',
                url: "cors.php?" + parametrizedurl, // notice I will call a file in my own domain, and append the parametrized url as per API specs
                dataType: 'jsonp',  // data type jsonp (i.e., padded json)
                jsonp: 'jsonp_callback', // jsonp_callback is part of the parametrizedurl, and when it gets passed on the url, a random function is generated and appended. You would see something similar to this jQuery19103874713401310146_1385178790322
                complete: function(var_x){
    
                    console.log('COMPLETE');
                    console.log(this);
                    console.log(var_x);
    
                },          
                success: function (data) {
                    console.log('SUCCESS');
                    console.log(data);
                    $("#thestates").append(data);               
                },
                error: function(xhr, textStatus, errorThrown) {
    
                    console.log('ERROR');
                    console.log('textStatus: ' + textStatus);
                    console.log('xhr: ' + xhr);
                    console.log('errorThrown: ' + errorThrown);
    
                }
            });
        }
    
        $( "#loadstates" ).click(function() {
    
            var bystate = "url=http://data.hud.gov/Housing_Counselor/search&AgencyName=&City=&State=CA&jsonp_callback="  // notice I included the parameter jsonp_callback and left the value empty
    
            loadJsonP(bystate);
    
        });
    
    });
    

    这个文件被这个html文件调用:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>Cross Domain Ajax Call</title>
    
            <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
            <script type="text/JavaScript" src="cfpb.js"></script>
        </head>
        <body>
            <div id="myDiv"><h2>Generate a List</h2></div>
            <button type="button" value="Submit" id="loadstates">Load</button>
            <div id="thestates"></div>
        </body>
    </html>
    

    当我执行单击按钮时,将对我自己服务器上的 cors.php 文件进行 ajax 调用:

    <?php
        if(isset($_GET)){
    
            $theurl = $_GET['url'].'/?';
            array_shift($_GET); // I remove the url parameter to easily create the parameter part of the url 
    
            $theurl .= http_build_query ($_GET); 
    
            $fhandle = fopen($theurl, 'r'); // I begin to read each line served to me by the API
            $data = array();
    
            $i = 0;         
            while(($buffer = fgets($fhandle)) !== false)
            {
                $temparray = explode(';',$buffer);
                $data[$i] = $temparray;
                $i++;
            }
    
            fclose($fhandle);
    
            $data = json_encode($data);
    
            echo $_GET['jsonp_callback']."(".$data.")"; // this results in the formatted json data PADDED (i.e., jsonp) by the autogenerated jsonp_callback value by the brower (i.e., jQuery19103874713401310146_1385178790322) 
    
        }
    
    ?>
    

    在这个例子中,我可以通过 Chrome 的控制台看到数据数组并插入到页面 div#thestates

    【讨论】:

      猜你喜欢
      • 2012-04-05
      • 1970-01-01
      • 2014-07-18
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多