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>";


})



原作者:
...