多个YQL-json数据请求/返回

时间:2015-05-16 00:44:09

标签: javascript php mysql json yql

我回到这里遇到这个问题: 我有一个API页面,我可以根据请求获取子数据文件。

所以我创建了一个js文件,它通过yql获取跨域json并将json数据解码为一个字符串,我将其传递给php,插入到MySql数据库并返回到表中。

所以我知道我可以用这样的网址查询API .... / usd-gold.json我得到有关美元和黄金之间交换的信息,但如果我想得到相反的改变我应该询问。 ... /金usd.json。

这是最后的问题。 如何获取多个json询问以获取json数据,解码它,组合数据并将其发送到php。 换句话说:我如何进行多重审讯,如idr-gold.json,gold-dir.json,usd-gold.json,gold-use.json等所有货币,组合代码,传递给php并研究mysql。

这是我使用的代码,用于一个查询。

JS代码/文件:

// JavaScript Document
$(document).ready(function(){
var container = $('#target');
$('.ajaxtrigger').click(function(){
doAjax($(this).attr('href'));
return false;
});
function doAjax(url){
// if it is an external URI
if(url.match('^http')){
  // call YQL

  // TEST

 $.getJSON("http://query.yahooapis.com/v1/public/yql?"+
            "q=select%20*%20from%20html%20where%20url%3D%22"+
            encodeURIComponent(url)+
            "%22&format=json'&callback=?",  // QUESTO è URL cui segue la "," e poi function(data)

    // this function gets the data from the successful 
    // JSON-P call
    function(data){

      // if there is data, filter it and render it out
        if(data.results[0]){
            var data = filterData(data.results[0]);

            container.html(data);
   //               alert(data);    // MIO TEST
            document.getElementById("prova1").value = data; //MIO

  // TEST

            var obj = $.parseJSON(data);
            document.getElementById("provabis").innerHTML = obj.buy.currency+"/"+obj.sell.currency+" "+obj.offer[0].rate+" "+obj.offer[0].amount+"  "+obj.offer[0].seller.name;
 //             alert(obj.sell.currency);

 // TEST END

      // otherwise tell the world that something went wrong
      } else {
        var errormsg = "<p>Error: can't load the page.</p>";
        container.html(errormsg);
      }
    }
  );
// if it is not an external URI, use Ajax load()
} else {
  $('#target').load(url);
}
}
// filter out some nasties
function filterData(data){
data = data.replace(/<body>/,'');
data = data.replace(/<?\/body[^>]*>/g,'');
data = data.replace(/[\r|\n]+/g,'');
data = data.replace(/<--[\S\s]*?-->/g,'');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
data = data.replace(/<script.*\/>/,'');
return data;
}
});

这里是html代码/文件:

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"  "http://www.w3.org/TR/html4/strict.dtd">

 <html>

 <head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> </meta>
    <title>

        Under Developement

    </title>
    <link type="text/css" href="styles.css" rel="stylesheet"></link>

 </head>
 <body>
    <div id="doc" class="yui-t7">
        <div id="hd" role="banner">
            <h1>
                Ajax with jQuery - using YQL
            </h1>
        </div>
        <div id="bd" role="main">
            <h2>
                Demo
            </h2>
            <ul>
                <li>
                    <a class="ajaxtrigger" href="ajaxcontent.html">
    Load Ajax Content
 </a>
 </li>
 <li>
 <a class="ajaxtrigger" href="http://www.API LINK.json"> 
 <!--                       <a class="ajaxtrigger" href="http://www.API LINK.json
                    </a><br>
   <a class="ajaxtrigger" href="http://www.API LINK.json"> 
 <!--                       <a class="ajaxtrigger"  href="http://www.API LINK.json"> -->
                        Get cspro2.json
                    </a>
                </li>
            </ul>
           <div id="target">
           </div>
            <h2>
            Formatted List
            </h2>
        </div>
          <div id="prova2">
          </div>
            <h2>
           TEST
            </h2>
        </div>
 <form action="jsontodb10.php" method="post">       
 Json code: <br>
 <textarea id="prova1" style="width:40%;height:40em;" name="jsonCode"> </textarea>
 <!-- metti qui il pulsante per submittare al php -->
 <br>
 <input type="submit">
 </form>



    <textarea id="provabis" style="width:40%;height:40em;"></textarea>
    <script src="http://code.jquery.com/jquery-latest.pack.js">  </script>
    <script src="code.js"></script>
    <script src="using-yql7.js"></script>




    </div>

</body>

</html>

最后是php代码/文件:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <link href="table-db.css" rel="stylesheet" type="text/css">
 <title>Database show</title>
 </head>

 <body>
 <?php
 //inserisci il reset della variabile che non manda in loop il force  update

 $submitVerify = $_POST["_Submit"];
 if($submitVerify=="force Update"){
 //     unset($submitVerify);
 echo ("<script type='text/javascript'>location.reload();</script>");
    };

 //connect to mysql db
 $servername = "localhost";
 $username = "my user";
 $password = "";
 $dbname = "my db";

 // Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);

 // Check connection
 if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
 }
 echo "Connected successfully <br />";


 // QUI METTIAMO la verifica circa il RecordTime ed il TimeNow (così  che non si registrino più di 1 Record/ 2 hour)
 $timeNow = date('Y-m-d H:i:s'); // ora adesso
 $time = strtotime($timeNow); // settato l'ora adesso
 $timeRange = date('Y-m-d H:i:s',strtotime('-2 hours', $time)); // l'ora adesso -2 ore

 $sqlsearchTime = "SELECT DateTimeSave FROM Valuta ORDER BY ID DESC  LIMIT 1";
 $searchresultTime = mysqli_query($conn, $sqlsearchTime);

 if (mysqli_num_rows($searchresultTime) > 0) {
 // output data of each row
 while($row = mysqli_fetch_assoc($searchresultTime)) {

    echo "\n Last record in database was at: " . $row["DateTimeSave"].   "<br>";

            if ($row["DateTimeSave"] > $timeRange) // se l'orario estratto dal database è < dell'orario attuale -2 ore
            {
                echo('hey sono passate meno di due ore, non inserirò un  altro dato a meno che tu non mi forzi <br />');  // allora apri il database  ed inserisci l'ultimo dato ottenuto e mostra il contenuto del database
 //                 goto showData;
                goto insertData;
            }
                else                 // se l'orario è maggiore
            {
                echo('si che possiamo mettere questo nuovo dato nel  database <br />'); // allora mostra solo il contenuto e rimanda a al tasto  che forza l'estrazione del dato e l'inserimento dei dati ne db e mostra  contenuto
                goto insertData;
            };      
 }
 } else {
 echo "0 results";
 };

 // NOME funzione
 insertData:
 //VALUES from JSON
 //read the json file contents
 //$jsondata = file_get_contents('idr-gold.json');
 //$jsondata = file_get_contents('idr-gold.txt');

 //convert json object to php associative array
 //$data = json_decode($jsondata, true);
 //get the value details
 $content = $_POST["jsonCode"];

 //$jsondata = file_get_contents('idr-gold.txt');
 //$json = json_decode($content, true);

 //convert json object to php associative array
 $data = json_decode($content, true);
 $buycurrency = $data['buy']['currency'];
 $sellcurrency = $data['sell']['currency'];
 $sellrate = $data['offer'][0]['rate'];
 $sellamount = $data['offer'][0]['amount'];
 $sellername = $data['offer'][0]['seller']['name'];
 $offer = $data['offer'];

 //se l'offerta nulla metti "no record"
 if($offer === NULL)
  {
    $sellrate = 'No Record';
    $sellamount = 'No Record';
    $sellername = 'No Record';
  };

 //VALUES RECORDSNORECORDS (OK) questo setta se c'è o meno un Record
 if($sellername != NULL)
 {
    $recordsNoRecords = TRUE;
 } else {
    $recordsNoRecords = FALSE;
 };

 //VALUES DATE&HOUR (OK) qui setta l'ora dell'inserimento e poi inserisce i dati
date_default_timezone_set('UTC+1');
$timestamp = date('Y-m-d H:i:s');



  $sqlinsert = "INSERT INTO Valuta  (BuyCurrency,SellCurrency,SellRate,SellAmount,SellerName,LinktoPage,Records NoRecords,DateTimeSave) 
      VALUES   ('$buycurrency','$sellcurrency','$sellrate','$sellamount','$sellername','test','$recordsNoRecords','$timestamp')";


 if ($conn->query($sqlinsert) === TRUE) {
 echo "New record created successfully <br />";
 } else {
 echo "Error: " . $sqlinsert . "<br>" . $conn->error;
 } goto showData;




 // NOME funzione
 showData:
 // QUERY X VEDERE
 $sqlsearch = "SELECT BuyCurrency, SellCurrency, SellRate, SellAmount,  SellerName, LinktoPage, DateTimeSave FROM Valuta";
 $searchresult = mysqli_query($conn, $sqlsearch);


 if (mysqli_num_rows($searchresult) > 0) {

// output data of each row
while($row = mysqli_fetch_assoc($searchresult)) {
    echo "\n Currency to buy: " . $row["BuyCurrency"]. " - Currency to  sell: " . $row["SellCurrency"]. " - Sell Rate " . $row["SellRate"]. " -  Amount on sale: " . $row["SellAmount"]. " - Seller Name: " .  $row["SellerName"]. " - Lik to page: " . $row["LinktoPage"]. " - Date &  Time of record: " . $row["DateTimeSave"].  "<br>";
 }
 } else {
 echo "0 results";
 };
 $conn->close();
 ?> 

 <!-- bottone per forzare l'aggiornamento -->

    <form name="update" action="" method="post">
    se vuoi forza
    <input type="submit" name="_Submit" value="force Update">
    </form>
    <?php
    $submit = $_POST["_Submit"];
    if($submit=="force Update"){
    echo ("facciamolo!");
 //     goto insertData;
    }else{
    echo ("SUCA!!");
 //     goto showData;
 };
 ?> 

 <br />
 <br />
 <br />
 <br />



 <?php
 // TABELLA
 //connect to mysql db
 $servername = "localhost";
 $username = "";
 $password = "";
 $dbname = "my db";

 // Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);

 // Check connection
 if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
 }
 echo "Connected successfully <br />";

 $sql = "SELECT    BuyCurrency,SellCurrency,SellRate,SellAmount,SellerName,LinktoPage,DateTime Save FROM Valuta ORDER BY ID DESC LIMIT 1";
 $result = $conn->query($sql);

 if ($result->num_rows > 0) {
 echo '<table cellpadding="0" cellspacing="0" class="db-table">';
 echo '<tr><th>Buy</th><th>Sell</th><th>Rate</th><th>Amount</th> <th>Seller</th><th>Link</th><th>Time Record</th></tr>';
 // output data of each row
 while($row = $result->fetch_assoc()) {
    echo "<tr><td>".$row["BuyCurrency"]."</td> <td>".$row["SellCurrency"]."</td><td>".$row["SellRate"]."</td> <td>".$row["SellAmount"]."</td><td>".$row["SellerName"]."</td> <td>".$row["LinktoPage"]."</td><td>".$row["DateTimeSave"]."</td></tr>";
 }
 echo "</table>";
 } else {
 echo "0 results";
 };
 $conn->close();
 ?>

 </body>
 </html>

提前求助!

UPDATE脚本

脚本的一个部分是有一个网站,我可以从一个返回json或xml的api中显示检索到的数据。

所以我尝试了在我看来最容易检索json数据的方法(如果我理解的话,xml会更难)。我发现使用json文件很容易获得YQL的跨域数据。

我读到的是,json回答,当你试图同时访问不同的文件时,可能有传输速率限制,我检查实时的json数据大约1/2秒给出答案。

所以这就是我的想法。 我创建了一个js表单,创建了api答案的url,我将数据抛出YQL,将该代码发送到php并将其插入到db中。因此,尽管必须等待站点实时获取所有数据,用户才能获取带有已保存数据的mysql表。

对我来说,最佳目标是: 1)有一个db,每4小时从api获得json; 2)更新保存的数据; 3)当用户打开页面可以实时查询db或强制json数据检索时(更新db)。

那是最后的一部分。 感谢你的时间。

0 个答案:

没有答案
相关问题