【问题标题】:JQuery Ajax Cross Domain Request and work with JSON StringJQuery Ajax 跨域请求和使用 JSON 字符串
【发布时间】:2014-11-20 07:01:18
【问题描述】:

我想创建一个自动完成功能,我需要来自不同网站的数据作为源。因此,当我手动访问链接时,我想创建一个 Ajax 请求作为第一步,它只返回 JSon 字符串(我认为它是 Json)。由于“允许来源”的事情,我遇到了一些错误。

这是我从中获取所有数据的链接:

http://www.futhead.com/15/players/search/quick/?term=

最后(在 term= 之后)我想稍后添加我的自动完成字段的输入,这个链接返回我的不同结果。

这是我在谷歌搜索后尝试过的,它会提示“错误”:

$.ajax({
     url:"http://www.futhead.com/15/players/search/quick/",
     data: "term=Ibarbo",
     dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
     success:function(json){
         // do stuff with json (in this case an array)
         alert("Success");
     },
     error:function(){
         alert("Error");
     }      
});

我想要什么:

我想在我的 php 文件中显示这个页面的结果,按属性排序。

这是“http://www.futhead.com/15/players/search/quick/?term=ibarbo”的结果:

[{"rating": 75, "club_image": "http://futhead.cursecdn.com/static/img/15/clubs/1842.png", "image": "http://futhead.cursecdn.com/static/img/15/players/204550.png", "revision_type": null, "workrates_short_string": "M/M", "xb_auction_average": null, "full_name": "V\u00edctor Ibarbo", "player_id": 204550, "id": 816, "nation_image": "http://futhead.cursecdn.com/static/img/15/nations/56.png", "pc_auction_average": null, "type": "15-player", "short_name": "V\u00edctor Ibarbo", "ps_auction_average": null, "club": 363, "nation": 12, "attr6": 78, "attr4": 80, "attr5": 39, "attr2": 71, "attr3": 66, "attr1": 91, "slug": "victor-ibarbo", "league": 1, "rare": true, "level": 0, "position": "ST"}]

那我要输出:

评分 = 75

Club_image = http://futhead.cursecdn.com/static/img/15/players/204550.png

等等。

【问题讨论】:

    标签: php jquery ajax json


    【解决方案1】:

    使用 JSONP,jQuery 创建一个&lt;script&gt; 标记并将函数名称发送到远程主机。远程主机需要将他们的结果包装在函数中,以便 jQuery 以后可以调用该方法来获取结果。

    请看这里:jasonp cross domain request "wrapping json into a callback method"

    如果远程主机没有通过包装结果来响应 jQuery 的 JSONP,那么您最好的解决方案可能是使用 PHP 中的 CURL 请求调用服务。您在自己的站点上创建一个返回结果的 PHP 页面,然后您不再有跨站点问题。

    我已使用以下代码向其他服务器发出请求,在我的情况下,由于需要凭据,我已将其删除,但它也应该可以在您自己的服务器上返回结果。 (注意,我可能在删除凭据等方面产生了一个错误,因此不确定这是否完美)。

    <?php
    namespace WebServices {
    
        class CurlRequest {
            const REQUEST_TYPE_GET      = 'GET';
            const REQUEST_TYPE_POST     = 'POST';
            const REQUEST_TYPE_PUT      = 'PUT';
            const REQUEST_TYPE_DELETE   = 'DELETE';
    
            public function get($path, array $params=array() ) {
                return $this->httpRequest(self::REQUEST_TYPE_GET,$path,$params);
            }
            public function post($path, array $params=array() ) {
                return $this->httpRequest(self::REQUEST_TYPE_POST,$path,$params);
            }
            public function put($path, array $params=array() ) {
                return $this->httpRequest(self::REQUEST_TYPE_PUT,$path,$params);
            }
            public function remove($path, array $params=array() ) {
                return $this->httpRequest(self::REQUEST_TYPE_DELETE,$path,$params);
            }
            protected function httpRequest($type, $path, array $params=array()) {
                if( $type == self::REQUEST_TYPE_GET || $type == self::REQUEST_TYPE_DELETE) {
                    $queryParams    = count($params)==0 ? '' : '&'.http_build_query($params);
                    $path          .= $queryParams;
                }
    
                $curl               = curl_init($path);
    
                if( $type == self::REQUEST_TYPE_POST || $type == self::REQUEST_TYPE_PUT ) {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params)); //-d
                    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); //-H
                }
                curl_setopt($curl, CURLOPT_VERBOSE, false); //-v
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $type);
    
                $response   = curl_exec($curl);
                $error      = curl_error($curl);
                $className  = get_class($this);
                curl_close($curl);
    
                if( $response === false || !empty($error) ) {
                    $err    = empty($error)
                            ? "{$className}::httpRequest to '{$path}' failed"
                            : "{$className}::httpRequest to '{$path}' failed with message ({$error})\r\nRESPONSE: '{$response}'";
                    error_log($err);
                    throw new \Exception($err);
                }
    
                return json_decode($response);
            }
        }
    }
    

    在您想要返回详细信息的页面上,您只需执行以下操作:

    $curlRequest = new CurlRequest();
    echo json_encode($curlRequest->get('http://www.futhead.com/15/players/search/quick/?term=ibarbo'));
    

    您也可以去掉方法中的 json_decode,这样它只会返回字符串,然后您不必在为您的服务输出之前重新编码。

    【讨论】:

    • 这对我有用,谢谢sn-p!现在我仍在努力访问每个数组元素的属性,例如属性“评级”。我尝试了以下方法: $result = $curlRequest->get($url); echo print_r($result[0]['rating']); .打印整个数组元素有效。
    • @kentor,要通过 $result[0]['rating'] 访问评级,您需要确保将 json_decode 中的第二个参数设置为 true(例如 json_decode($results,true)。否则,您需要以 $result[0]->rating 的形式访问它。
    • 非常感谢您的帮助。你为我节省了很多时间:)
    猜你喜欢
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2012-08-01
    • 2010-10-19
    相关资源
    最近更新 更多