尝试将使用SQL语句生成的JSON数据从PHP脚本返回到JS网页,但是获取null

我想按下提交按钮,从PHP脚本中的结果SQL语句返回JSON数据,但我收到null

我将使用返回的JSON在我的Google地图上过滤显示标记,但是现在我只想将数据从PHP脚本返回到我的jQuery页面,以便我可以操作/使用它。

提交按钮

HTML

  

JS

 $('#myform').on('submit', function(e) { e.preventDefault(); var myData = $('#myform').serializeArray(); $.getJSON('myscript.php', myData, function(json){ alert(json);// actually filter for later }); }); 

PHP脚本

 // action is a hidden form control I use to check if form was submitted if(isset($_POST["action"])){ if(isset($_POST["color"]) && isset($_POST["zipcode"])){ // try to open a connection to a MySQL server $connection = mysql_connect($host, $username, $password) or die("Could not connect" . mysql_error()); // select the active MySQL database to work with $db_selected = mysql_select_db($database, $connection) or die("Can\'t use db:" . mysql_error()); $query = 'sql statement to return resutls based on what color and zipcode was provided'; $result = mysql_query($query) or die("Can\'t do that: " . mysql_error()); } // close connection to the database echo json_encode($result); mysql_close($connection); } 

您不能直接返回mysql_query调用的结果对象。 首先必须使用mysql_fetch_array或类似函数( PHP文档 )解析它。

 ... $result = mysql_query($query); if ( $result === false ) { die("Can\'t do that: " . mysql_error()); } $retVal = array(); while( $row = mysql_fetch_array( $result ) ) { $retVal[] = $row; } ... echo json_encode( $retVal ); 

编辑

根据getJSON ( 链接 )的jQuery规范,数据使用GET参数发送,而不是使用POST。 因此,您必须将PHP代码中的所有$_POST外观更改为$_GET$_REQUEST

除此之外,如果未设置变量,则应返回一些错误消息。 现在(根据您的代码)只返回一个空文档。

在echo之前,您应该声明返回的内容类型:

 header('Content-Type: application/json'); 

如果您想检查数据的接收情况,可以使用:

 $.ajax({ url: url, data: myData, success: function(json) {}, error: function(json) {} // this should allow you to check if data is received (but since the content type is set to text/html and $.getJSON expectr application/json it won't be a success) });