简体   繁体   English

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

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

I want to create a autocomplete function, where I need data as source from a different website. 我想创建一个自动完成功能,在这里我需要来自不同网站的数据作为来源。 Therefore I want to create as first step a Ajax Request which just returns me the JSon String (I think it is Json), when I visit the link manually. 因此,我想首先创建一个Ajax请求,当我手动访问该链接时,该请求仅向我返回JSon字符串(我认为是Json)。 I experienced some errors because of the "Allow Origin" thing. 由于出现“允许原点”,我遇到了一些错误。

This is the Link where I get all the data from: 这是我从中获取所有数据的链接:

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

In the end (after term=) I want to add the input of my autocomplete field later and this link returns my different results for this. 最后,在term =之后,我想稍后添加我的自动完成字段的输入,并且此链接为此返回不同的结果。

This is what I've tried after googling a lot, which alerts "Error": 这是我在大量搜索之后尝试执行的操作,它会提示“错误”:

$.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");
     }      
});

What I want: 我想要的是:

I want to display the results of this page in my php file sorted by the attributes. 我想在按属性分类的php文件中显示此页面的结果。

This is the result of " http://www.futhead.com/15/players/search/quick/?term=ibarbo ": 这是“ 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"}]

Then I want to output: 然后我要输出:

Rating = 75 等级= 75

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

and so on. 等等。

With JSONP, jQuery creates a <script> tag and sends a function name to the remote host. 使用JSONP,jQuery创建<script>标记并将函数名称发送到远程主机。 The remote host needs to wrap their results in the function so that jQuery can later call the method to get the results. 远程主机需要将其结果包装在函数中,以便jQuery稍后可以调用该方法以获取结果。

See Here: jasonp cross domain request "wrapping json into a callback method" 请参阅此处: jasonp跨域请求“将json包装到回调方法中”

If the remote host doesn't respond to jQuery's JSONP by wrapping the results, then it is likely that your best solution will be to call the service with a CURL request in PHP. 如果远程主机没有通过包装结果来响应jQuery的JSONP,那么最好的解决方案可能是在PHP中使用CURL请求来调用服务。 You create a PHP page on your own site that returns the results, and then you no longer have a cross-site problem. 您在自己的网站上创建一个返回结果的PHP页面,然后您不再遇到跨站点问题。

I've used the below code to make requests to other servers, in my case due to the need for credentials, which I stripped out, but it should also work to return the results on your own server. 在我的情况下,由于需要凭据,因此我使用了以下代码向其他服务器发出请求,我将其剥离了,但它也可以在您自己的服务器上返回结果。 (Note, I may have created a bug in stripping out the credentials, etc., so not sure this works perfectly). (请注意,我可能在剥离凭据等方面创建了一个错误,因此不确定该操作是否完美)。

<?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);
        }
    }
}

On the page that you want to return the details, you would just need to do something like: 在您要返回详细信息的页面上,只需执行以下操作:

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

you could also get rid of the json_decode in the method so it will just return the string and then you don't have to re-encode before outputting it for your service. 您还可以摆脱方法中的json_decode,这样它只会返回字符串,然后在为服务输出之前不必重新编码。

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

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