我正在尝试在我的主 PHP 文件中调用 PHP 脚本。我想显示 PHP 脚本的结果以及正在运行的 SQL 查询。
我还想包括动态显示结果/不刷新页面的可能性。
这是我到目前为止所尝试的,我对 Jquery 和 AJAX 很陌生。提前致谢!
工作 fiddle :http://jsfiddle.net/52n861ee/ 这就是我想要做的,但是当我点击它时会告诉我错误:第 23 行(“我正在使用 json_encode
JQuery/AJAX 部分:
<div id="map_size" align="center">
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$(".desk_box").click(function() {
$id = $(this).attr("data")
$("#station_info_"+$id).toggle();
$.ajax({
url:"display_stationinfo.php",
type: "GET",
success:function(result){
$("#station_info_"+$id).html(result);
}});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php(我要调用的脚本):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while($row = mysqli_fetch_assoc($station_result)){
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
$html = "<div class='station_info' id='station_info".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
}//end while loop for station_result
echo $_GET['callback'] . '(' .json_encode($html) . ')';
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
最佳答案
三个问题:
在 PHP 脚本中,您将 html 字符串视为对象或数组 --- 您无法将字符串文字输出为 JSON
在 JS 脚本中,您将“JSON”[对象] 视为字符串文字或 html 对象 --- 您不能以这种方式输出 JSON,您需要使用 DOT表示法来访问其数据。
尽管您的 PHP 脚本似乎正在发送
JSONP
,但您尚未在ajax 中指定
调用。jsonp
dataType
假设您的所有 PHP 脚本都位于同一域中,请更改 echo $_GET['callback'] 。 '(' .json_encode($html) . ')';
到:
echo $html;
这样你的 PHP 输出与你的 JS 期望的一致。
关于javascript - 如何使用 JQuery 切换和 AJAX 调用 PHP 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26363123/