javascript - javascript從PHP接收空對象

129 5

我正在嘗試從PHP發送一個JSON對象到Javascript,我是PHP的新手,所以遇到了一些問題,我所有的HTML,PHP和javascript代碼都包含在一個PHP文件中。

我已經嘗試json_encode,從javascript中獲取變數,並且沒有錯誤,但是,仍返回NULL對象。


<?php


 $street = $city = $state = $location = $url = $lat = $lon ="";


 $geolocation = $coords = $temp = $details = null;


 $temparray = array();



 if ($_SERVER["REQUEST_METHOD"] =="POST") {


 if(isset($_POST['location']) && $_POST['location'] == 'Yes'){


 $geolocation = json_decode($_POST["geolocation"]);


 $lat = $geolocation->lat;


 $lon = $geolocation->lng;


 $details = find_forecast($lat, $lon);


 }else{


 $street = $_POST["street"];


 $city = $_POST["city"];


 $state = $_POST["state"];


 $temparray = find_coords($street, $city, $state);


 $lat = $temparray[0];


 $lon = $temparray[1]; 


 $details = find_forecast($lat, $lon);


 }


 }


?>




<script type="text/javascript">


 document.getElementById('theform').addEventListener('submit', 


 function(evt){


 evt.preventDefault();


 var stuff ="<?php echo json_encode($details); ?>"; //tried 2 ways 


 to achieve


 var arr = JSON.parse("<?php echo json_encode($details); ?>"); //2nd 


 way to test if it would work


 console.log(arr);


 document.getElementById("timezone").innerHTML ="<p 


 id='timezone'>" + arr.timezone +"</p>";


 })



這是我的javscript代碼,我嘗試在其中檢索JSON對象,對它進行編碼並進行解析,


<form id="theform" onSubmit="return checkInput()" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" target="testiframe">


 <h2><i>Weather Search</i></h2>


 <label for="street"><b>Street</b></label>


 <input id="street" name="street" type="text" value="">


 <div class="sub-entry">


 <input type="checkbox" id="location" name="location" value="Yes"> 


 Current Location


 </div>


 <br><br>


 <label for="city"><b>City</b></label>


 <input id="city" name="city" type="text" value="">


 <br><br>


 <label for="state"><b>State</b></label>


 <select name="state" id="state">


 <option value="state">State</option>


 <option value="line">----------------</option>


 <option value="AL">Alabama</option>


 <option value="AK">Alaska</option>


 </select>


 <br><br><br><br>


 <div class="button">


 <input id="search" name="Search" onclick="checkInput()" 


 type="submit" value="Search">


 <input id="clear" name ="clear" onclick="clearform()" 


 type="button" value="Clear">


 </div>


</form>


<div id="blue" class="blue">


<p id="timezone"></p>


</div>



时间: 原作者:

120 2

使用時不要在JavaScript中放置引號 <?php echo json_encode(...) ?>你也不需要調用JSON.parse() (但是如果這樣做的話,你必須將它放在單引號中,因為JSON本身使用雙引號)。


<script type="text/javascript">


document.getElementById('theform').addEventListener('submit', function(evt){


 evt.preventDefault();


 var stuff = <?php echo json_encode($details); ?>;


 console.log(stuff);


 document.getElementById("timezone").innerHTML ="<p id='timezone'>" + stuff.timezone +"</p>";


})



原作者:
...