使用从表单构建的 url 生成 json

Generate json with url built from form

我正在尝试创建一个能够生成多个 url 的表单,具体取决于用户的输入。创建的 url 具有 json 扩展名。 php 文件用于获取 url 的内容。此 php 文件必须与输入的 url 具有相同的内容。此 php 文件用作 javascript/jquery 文件的输入。

在这个文件中,我试图将 json 代码转换为 html table。这是由 http_request 完成的。 table 必须在 html 页面上的 div 中输出。但是,由于找不到错误,我的代码无法正常工作。我已经在 Whosebug 和 google 上查看了类似的问题,但可以找到使我的代码正常工作的修复程序。

我正在将此代码应用于 Spotify 列表。这是我已有的代码:

html:

<script type="text/javascript" src="spotify.js"></script>
<form id="spotifyform" action="spotifylist.php" method="post">
      <select id="country" name="country">
        <option value="GB">UK</option>
        <option value="US">USA</option>
      </select>
      <select id="interval" name="interval">
        <option value="daily">Daglijst</option>
        <option value="weekly">Weeklijst</option>
      </select>
      <select id="chart" name="chart">
        <option value="most_streamed">Meest gestreamd</option>
        <option value="most_viral">Meest gedeeld</option>
      </select>
      <input type="submit" name="formSubmit" value="Submit"/>
</form>
<div id="spotifylist"></div>

spotify.js:

function loadJSON()
{
    var http_request = new XMLHttpRequest();
    try{
      // Opera 8.0+, Firefox, Chrome, Safari
      http_request = new XMLHttpRequest();
    }catch (e){
      // Internet Explorer Browsers
      try{
         http_request = new ActiveXObject("Msxml2.XMLHTTP");
      }catch (e) {
         try{
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
         }catch (e){
            // Something went wrong
            alert("Your browser broke!");
            return false;
         }
      }
    }

   http_request.open("GET", "spotifylist.php", true);
   http_request.send();
   http_request.onreadystatechange  = function(){
      if (http_request.readyState == 4  )
      {
        // Javascript function JSON.parse to parse JSON data
        var jsonObj = JSON.parse(http_request.responseText);

        // jsonObj variable now contains the data structure and can
        // be accessed as jsonObj.artist_name and jsonObj.track_name.

        HTML = "<table id='chart'> <thead><tr id='row2'><th id='dw'></th><th   id='song'>Artiest</th><th id='song'>Titel</th></tr></thead><tbody>";
        var x=jsonObj.tracks;
        for (i=0;i<x.length;i++)
          { 
        HTML += "<tr id='row1'><td id='dw'>";
        HTML += i+1;
        HTML += "</td><td id='song'>";
        HTML += x[i].artist_name;
        HTML += "</td><td id='song'>";
        HTML += x[i].track_name;
        HTML += "</td></tr>";
          }
        HTML += "</tbody></table>";

        document.getElementById("spotifylist").innerHTML = HTML; 

      }
    }
 }

$("#spotifyform").submit(function(){
    loadJSON();
    return false;
});

spotifylist.php

<?php 
if($_POST['formSubmit'] == "Submit") 
{
   $chart = $_POST['chart'];
   $country = $_POST['country'];
   $interval = $_POST['interval'];
}

$data_file="http://charts.spotify.com/api/tracks/".$chart."/".$country."/".$interval."/latest";
$url = file_get_contents ($data_file);
echo $url;
?>

当前出现的问题是当我按下提交按钮时加载了 php 文件。此文件包含正确的 json 信息。但是,此 json 未转换为 html table.

如果有人能帮我解决这个问题,我将不胜感激

如果您希望 spotifylist div 在您按下提交时加载数据,您必须阻止页面重定向。

制作表单动作:

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>

如果可能,您的输入值(如果您在表单标签中有任何值):

"<?php echo $_POST['value']?>"

如果可以,请将您的 HTML 代码放在 PHP 文件中,该文件执行 spotifylist.php.

中的所有内容

我的猜测有几个问题。

您将表单发送到 spotifylist.php,它抓取一个文件并将某些内容发送回 html。可能 JSON 但你在哪里处理这些数据? 也许一些 Javascript 对你的 php 发回的 "string" 做些什么?

并且您的负载JSON 发送(每当)一个 GET 请求到同一个 php 但没有参数或其他东西。 所以你的 php 运行 变成了一个错误,因为显然没有设置 POST 变量,所以你的 if 条件中的变量永远不会设置,因此你的数据会再次返回?!?有错误

您应该首先清楚要使用哪种技术。

在我看来,你会两者兼顾。

    有多种方法可以从外部服务器获取信息:

  • httprequest - 不推荐,因为用户体验不好。
  • file_get_contents - 通常很容易,但在这种情况下需要大量数据处理。 Php 在服务器端工作,javascript 在客户端工作。让这两者一起工作需要做更多的工作。
  • $.ajax - 在这种情况下是最好的解决方案,因为它不需要任何 php 并且 $.ajax 能够直接解析 json 数据。因为数据是从外部站点请求的,所以您必须将数据类型更改为 jsonp 并执行回调函数。

  • 将数据从表单传输到javascript非常容易:

    // Automatically call this function when the page loads.
    window.onload = function loadJSON()
    {
      // The HTML input of the form that is the input of this javascript document
      var country2 = document.getElementById("country");
      var chart2 = document.getElementById("chart");
      var interval2 = document.getElementById("interval");
    

    在提交时使用选定的参数构建 url:

    // Call the function when the form is submitted
      $("#spotifyform").submit(function(e)
      {
        e.preventDefault(); // to prevent the page from reloading
    
        // Save the choice of the <select> country in a variable named country2
        var country = country2.options[country2.selectedIndex].value;
        var chart = chart2.options[chart2.selectedIndex].value;
        var interval = interval2.options[interval2.selectedIndex].value; 
        var url = "http://charts.spotify.com/api/tracks/" + chart + "/" + country + "/" + interval + "/latest"; // build url
    

    然后获取正确的数据,直接用json原生解析器解析。

    // Get the data from the site and save this into the variable 'json'
        $.ajax
        ({
          'url': url + '?callback=?', // ?callback=? lets the server generate a function name, the call can be handled in the success parameter
          'dataType': 'jsonp', // Cross site request via jsonp
          'error': function(xhr, status, error){ alert(error.message); },
          'success': jsonParser // call function
        }); // $.ajax  
    
      }); // $("#spotifyform").submit(function(e)
    } // window.onload = function loadJSON()
    

    然后随心所欲地处理数据。您不需要执行 httprequest,也不必再解析数据。

    function jsonParser(json) 
    {
      HTML = "<table id='chart'> <thead><tr id='row2'><th id='dw'></th><th id='song'>Artiest</th><th id='song'>Titel</th></tr></thead><tbody>";
      var x=json.tracks;
      for (i=0;i<x.length;i++)
        { 
        HTML += "<tr id='row1'><td id='dw'>";
        HTML += i+1;
        HTML += "</td><td id='song'>";
        HTML += x[i].artist_name;
        HTML += "</td><td id='song'>";
        HTML += x[i].track_name;
        HTML += "</td></tr>";
        }
      HTML += "</tbody></table>";
      document.getElementById("spotifylist").innerHTML = HTML; 
    } // function jsonParser(json)