簡體   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