获取外部JSON数据。 jQuery + AJAX的工作原理。 PHP + cURL没有

时间:2015-02-11 20:48:24

标签: php jquery ajax json curl

我坚持这个。我试图从远程服务器提取动态生成的JSON数据。这里只是生成JSON的URL:

https://www.librarything.com/api_getdata.php?userid=jtodd1973&key=1962548278&max=1&responseType=json

我可以使用jQuery / AJAX访问数据。这是我在jtodd.info/librarything.php上使用的代码:

            <div id="booklist">
                    <table id="tbl_books" style="width:80%; border: thin solid black;">
                            <tr style="border: thin solid black; background-color: #666; color: #fff;">
                                    <th style="width:40%;">Title</th>
                                    <th style="width:30%;">Author</th>
                                    <th style="width:10%;">Rating</th>
                                    <th style="width:20%;">Reading dates</th>
                            </tr>
                    </table>
            </div>

            <script type="text/javascript"> 
                    $(document).ready(function () {
                            $.ajax({
                                    type:'POST',
                                    callback: 'callback',
                                    crossDomain: true,
                                    contentType: 'application/json; charset=utf-8',
                                    dataType:'JSONP',
                                    beforeSend: function setHeader(xhr){ xhr.setRequestHeader('accept', 'application/json'); },
                                    url:'https://www.librarything.com/api_getdata.php?userid=jtodd1973&key=1962548278&booksort=title&showTags=1&showCollections=1&showDates=1&showRatings=1&max=1000',
                                    success:function(data) {
                                             x = 0;
                                             var data1 = JSON.stringify(data);
                                             var data2 = JSON.parse(data1);
                                             $.each(data2.books, function(i,book){
                                                     var date1 = Number(1420027199);
                                                     var date2 = Number(book.entry_stamp);
                                                     if (date2 > date1) {
                                                            x = x + 1;
                                                            var testTitle = book.title;
                                                            var n = testTitle.indexOf(" (");
                                                            if(n > -1) {
                                                                    var bookTitle = testTitle.substr(0, n);
                                                            } else {
                                                                    var bookTitle = testTitle;
                                                            }
                                                            var bookAuthor = book.author_lf;
                                                            var bookRating = book.rating;

                                                            if(x % 2 == 0){ 
                                                                    var rowColor = "#fff"; 
                                                            } else { 
                                                                    var rowColor = "#ccc"; 
                                                            }

                                                            $('#booklist table').append('<tr style="background-color:' + rowColor + ';">' +
                                                            '<td style="font-style: italic;">' + bookTitle + 
                                                            '</td><td>' + bookAuthor + 
                                                            '</td><td style="text-align: center;">' + bookRating + 
                                                            '</td><td> &nbsp;' +
                                                            '</td></tr>');
                                                     }
                                             });
                                    },
                                    error:function() {
                                            alert("Sorry, I can't get the feed");   
                                    }
                            });                
                    });                
            </script>

但是,我无法使用PHP&amp; amp;卷曲。我没有得到服务器的回复。更具体地说,我得到错误号7 / HTTP代码0.这里是我在jtodd.info/librarything2.php上使用的代码:

<?php
    $url = 'https://www.librarything.com/api_getdata.php?userid=jtodd1973&key=1962548278&max=1&responseType=json';
    $result = get_web_page( $url );
    if ( $result['errno'] != 0 )
            echo "<p>Error number = " . $result['errno'] . "</p>";
    if ( $result['http_code'] != 200 )
            echo "<p>HTTP code = " . $result['http_code'] . "</p>";
    $page = $result['content'];
            echo "<pre>" . $page . "</pre>";

    function get_web_page( $url ) {
            if(!function_exists("curl_init")) die("cURL extension is not installed");
            $ch = curl_init();
            $options = array(
                    CURLOPT_URL            => $url,
                    CURLOPT_RETURNTRANSFER => true,     // return web page
                    CURLOPT_HEADER         => true,    // don't return headers
                    CURLOPT_FOLLOWLOCATION => true,     // follow redirects
                    CURLOPT_ENCODING       => "",       // handle all encodings
                    CURLOPT_USERAGENT      => "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2", // who am i
                    CURLOPT_AUTOREFERER    => true,     // set referer on redirect
                    CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
                    CURLOPT_TIMEOUT        => 120,      // timeout on response
                    CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
                    CURLOPT_SSL_VERIFYPEER => false     // Disabled SSL Cert checks
            );
            curl_setopt_array( $ch, $options );
            $content = curl_exec( $ch );
            $err     = curl_errno( $ch );
            $errmsg  = curl_error( $ch );
            $header  = curl_getinfo( $ch );
            curl_close( $ch );

            $header['errno']   = $err;
            $header['errmsg']  = $errmsg;
            $header['content'] = $content;
            return $header;
    }

&GT;

感谢您的任何建议。

1 个答案:

答案 0 :(得分:0)

我刚试过你的代码 - 这就是我得到的回复:

HTTP/1.1 200 OK
Server: nginx
Date: Wed, 11 Feb 2015 20:53:34 GMT
Content-Type: application/json
Content-Length: 1102
Connection: keep-alive
Set-Cookie: cookie_from=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/
Set-Cookie: LTAnonSessionID=572521187; expires=Wed, 10-Feb-2016 20:53:34 GMT; path=/
lt-backend: 192.168.0.101:80

{"settings":{"amazonchoice":null,"show":{"showCovers":null,"showAuthors":null,"showTitles":null,"showRatings":null,"showDates":null,"showReviews":null,"showTags":null,"showCollections":null},"style":null,"title":null,"titleLink":null,"theuser":"jtodd1973","powered":"Powered by ","uniqueKey":null,"bookcount":1,"showWhat":null,"nullSetMsg":"No books found.","notEnoughImagesMsg":"Not enough books found.","domain":"www.librarything.com","textsnippets":{"by":"by","Tagged":"Tagged","readreview":"read review","stars":"stars"}},"books":{"112016118":{"book_id":"112016118","title":"As I lay dying : the corrected text","author_lf":"Faulkner, William","author_fl":"William Faulkner","author_code":"faulknerwilliam","ISBN":"067973225X","ISBN_cleaned":"067973225X","publicationdate":"1990","entry_stamp":"1409083726","entry_date":"Aug 26, 2014","copies":"1","rating":5,"language_main":"","language_secondary":"","language_original":"","hasreview":"0","dateacquired_stamp":"0","dateacquired_date":"Dec 31, 1969","cover":"https:\/\/images-na.ssl-images-amazon.com\/images\/P\/067973225X.01._SCLZZZZZZZ_.jpg"}}}

i.o.w。问题不在您的PHP代码中 - 您需要进一步查看(例如:找出您的IP是否因某种原因被阻止)