Javascript函数调用php

时间:2011-11-04 11:02:04

标签: javascript html json

我对网站的问题感到非常沮丧。从php文件中,我得到了这个JSON列表:

{"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurstel"},"Recipe_9":{"ID":"9","TITLE":"Schnitzel"},"Recipe_10":{"ID":"10","TITLE":null},"Recipe_19":{"ID":"19","TITLE":null},"Recipe_20":{"ID":"20","TITLE":"Hundefutter"},"Recipe_26":{"ID":"26","TITLE":"Apfelstrudel"},"Recipe_37":{"ID":"37","TITLE":null},"Recipe_38":{"ID":"38","TITLE":"AENDERUNG"},"Recipe_39":{"ID":"39","TITLE":null},"Recipe_40":{"ID":"40","TITLE":"Schnitzel"},"Recipe_42":{"ID":"42","TITLE":"Release-Test"},"Recipe_43":{"ID":"43","TITLE":"Wurstel2"}}},"Message":null,"Code":200}

在我的html文件中,我有一个JS函数解析这个JSON数据并将其保存到数组中。

<script type="text/javascript">
    function test() {
            //var availableTags = new Array(400);
            //availableTags[0] = "Test";
            alert("misstake");
            var availableTags = JSON.parse(<?php include("/php/search_new.php"); ?>);
            alert("misstake");
            //var availableTags = JSON.parse(<?php include("/php/getAllRecipes.php"); ?>);
            alert("misstake");
            for(var i=0;i<availableTags.length;i++){
                alert("<b>availableTags["+i+"] is </b>=>"+availableTags[i]+"<br>");
            } 
            alert("Hallo");
        }
    </script>

我确定,该函数被调用,因为我只是在其中发出了警报。 这是我的HTML:

<body>
        <form action="search.html" onsubmit="test()">
            <input  type="text" class="searchinput" style="margin-left: 850px; margin-top: 0px; width:170px; background: #fff url(images/search_icon.png) no-repeat 100%;" placeholder="Suchen..."></input>
            <input type="submit"  value="" width: 5px></input>
        </form>         
</body>

所以

一定有错误
var availableTags = JSON.parse(<?php include("/php/search_new.php"); ?>);

有什么问题?我怎么能弄明白呢?

如果你需要php:

<?php
include 'db_connect.php';
 session_start();
      if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 1200)) {
        session_destroy();   
        session_unset(); 
      }
      else
      {
        $_SESSION['last_activity'] = time();
      }
$arr = array('Data' => null,'Message' => null,'Code' => null);


$sql = "SELECT * FROM  RECIPES";
$result = mysql_query($sql,$db) or exit("QUERY FAILED!");
            while($row = mysql_fetch_array($result))
             {
                 $arr['Data']['Recipes']['Recipe_'.$row['recipes_id']]['ID'] = $row['recipes_id'];
                 $arr['Data']['Recipes']['Recipe_'.$row['recipes_id']]['TITLE'] = $row['title'];
             }
if($arr['Data'] == null)
{
    $arr['Message']= "nothing found";
    $arr['Code'] = 404;
}
else
{
    $arr['Code'] = 200;
}
mysql_close($db);
echo json_encode($arr);
?>

1 个答案:

答案 0 :(得分:1)

你不需要做JSON.parse就可以了。

var availableTags = <?php include("/php/search_new.php"); ?>;

并将您的php文件命名为somename.php,并确保它位于某个本地或托管服务器上。

您可以将数据视为

alert(a['Data']["Recipes"]["Recipe_5"]["ID"]);