如何基于表单选择生成JSON,通过使用对PHP脚本的jQuery AJAX调用来构建SQL语句

如何基于表单选择生成JSON,通过使用对PHP脚本的jQuery AJAX调用来构建SQL语句,php,jquery,sql,ajax,json,Php,Jquery,Sql,Ajax,Json,我有一个HTML表单(2个列表框和一个复选框),我想用它来过滤页面上的结果 当我按下Submit按钮(.onclick(function(){}))时,它将对本地服务器上的PHP脚本执行jQuery AJAX调用,首先,检查列表框中是否选中了任何内容,以及是否选中了该复选框,然后基于该复选框构建一条SQL语句来查询我的数据库并将结果检索为JSON 理论上,你会怎么做。我已经有了PHP脚本,可以简单地从表中获取所有内容并将其保存为JSON: <?php // databse connecti

我有一个HTML表单(2个列表框和一个复选框),我想用它来过滤页面上的结果

当我按下
Submit
按钮(
.onclick(function(){})
)时,它将对本地服务器上的PHP脚本执行jQuery AJAX调用,首先,检查列表框中是否选中了任何内容,以及是否选中了该复选框,然后基于该复选框构建一条SQL语句来查询我的数据库并将结果检索为JSON

理论上,你会怎么做。我已经有了PHP脚本,可以简单地从表中获取所有内容并将其保存为JSON:

<?php
// databse connection info
require("dbinfo.inc.php");

// try to open a connection to a MySQL server
$connection=mysql_connect($host, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}

// select the active MySQL database to work with
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}

// grab data about every campus and which instituion they belong to
$query = 'select statement to grab all the data from a table';
$result = mysql_query($query);

// check if $results has anything
if (!$result) {
  die('Invalid query: ' . mysql_error());
}

// time to start generating our huge XML
while ($row = @mysql_fetch_assoc($result)){
    $finalarray[] = $row;
    $main_arr['products'] = $finalarray;
}
//  close connection to the database
mysql_close($connection);

//  echo, save and write the file
// print json_encode($main_arr);

$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($main_arr));
fclose($fp);


?>

首先使用ajax从表单发送数据:

$('form').on('submit', function(e) {
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url : 'myPHPfile.php',
        data: {form : $('form').serialize()}
    }).done(function(data) {
         var myJSONresult = data;
    });
});
在PHP文件中,您将使用

$form = $_POST['form'];
无需保存到文件,只需通过回显将其发送回即可

echo json_encode($main_arr);

下面是一个发布到php文件并使用ajax获取数据的示例。 结果将被记录到控制台中。 我想您知道在检索json后如何使用js处理它

//the php
<?php

    //bla bla connect to database etc

    //if form has been submitted with ajax
    if(isset($_POST["ajax_request"])){

        //build query
        $id    = $_POST["id"];
        $fruit = $_POST["fruit"];
        $query = "SELECT * FROM fruits WHERE id=$id AND fruit='$fruit'";

        //fetch from db
        $result = mysql_query($query);

        //send out json
        die(json_encode($result));

    }

?>

//the jquery
<script type="text/javascript">

$(document).ready(function(){

    //on submit
    $("#ajaxForm").submit(function(e){

        //stop default page refresh
        e.preventDefault();

        //define the form
        var form = $(this);

        //get the form data
        var data = form.serialize();

        //send it via ajax
        $.ajax({
           type      : "post",
           dataType  : "json",
           url       : "url to your php here",
           data      : data+"&ajax_request=1",
           success   : function(json){
               console.log(json);
           },
           error     : function(a,b,c){
               console.log(a,b,c);
           }
        });

    });

});

</script>

//the html
<form id="ajaxForm" method="post" action="">
    <input type="text" name="id" required="required" placeholder="enter id"/>
    <input type="text" name="fruit" required="required" placeholder="enter fruit"/>
    <input type="submit" name="submit"/>
</form>
//php

如何访问PHP文件中表单控件的各个值?我的JavaScript将整个表单的值作为一个字符串获取,但我想单独访问它们。我不知道如何在PHP中访问表单控件的单独值。救命啊
$\u POST['form']
将表单数据视为单个字符串。因此,假设我有一个zipcode(
name=“zipcode”
id=“zipcode”
)字段-我不能像这样在PHP内部访问它:
$\u POST['zipcode']
。我使用adeneo的示例将表单数据从JS传递到PHP。