繁体   English   中英

jQuery Ajax跨域请求并使用JSON字符串

[英]JQuery Ajax Cross Domain Request and work with JSON String

我想创建一个自动完成功能,在这里我需要来自不同网站的数据作为来源。 因此,我想首先创建一个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

等等。

使用JSONP,jQuery创建<script>标记并将函数名称发送到远程主机。 远程主机需要将其结果包装在函数中,以便jQuery稍后可以调用该方法以获取结果。

请参阅此处: jasonp跨域请求“将json包装到回调方法中”

如果远程主机没有通过包装结果来响应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,这样它只会返回字符串,然后在为服务输出之前不必重新编码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM