Php 具有多个选择框条件的Ajax请求

Php 具有多个选择框条件的Ajax请求,php,sql,ajax,database,Php,Sql,Ajax,Database,首先,我要说的是,作为一种爱好,我刚刚开始学习Web开发的基础知识:html、css、javascript和php 我试图实现一个带有数据库查询的网页,但遇到了一些困难: 如果有人能告诉我该怎么做,我将不胜感激 我不想让你为我写完整的代码,但是是的,给我一些提示和线索 我有一张带有Id、项目、价格1、价格2和价格3的表 经过大量搜索,我成功地将所有项目动态加载到一个选择列表中,并在一个div上显示(price1),该div带有一个on-change事件,该事件基于通过ajax调用选择的项目 现在

首先,我要说的是,作为一种爱好,我刚刚开始学习Web开发的基础知识:html、css、javascript和php

我试图实现一个带有数据库查询的网页,但遇到了一些困难:

如果有人能告诉我该怎么做,我将不胜感激

我不想让你为我写完整的代码,但是是的,给我一些提示和线索

我有一张带有Id、项目、价格1、价格2和价格3的表

经过大量搜索,我成功地将所有项目动态加载到一个选择列表中,并在一个div上显示(price1),该div带有一个on-change事件,该事件基于通过ajax调用选择的项目

现在我需要根据另外两个选择列表更新这个价格分区:一个有3个值(a、b、c),另一个有(是或否)

如果选择列表2为(a),选择列表3为(是),则显示的价格为(价格2);如果选择列表2为(b),选择列表3为(是),则要显示的价格为(价格3),如果选择列表3选项为(否),则必须对加载的任何价格进行标记。全部使用ajax,不考虑选择的顺序

希望我说清楚。 如果需要,我可以加载我的代码

提前谢谢。 瓦斯科

这就是我到目前为止所做的:

Ajax.php

<?php
db connection variables


if(!isset($_GET['id'])){
    echo json_encode(array('success' => false, 'price_1' => '', 'message' => 'no id given'));
    exit;
}

try {
    $conn = new PDO("mysql:host=$servername;dbname=test", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    trigger_error("Connection failed: " . $e->getMessage());
    echo json_encode(array('success' => false, 'price_1' => '', 'message' => 'shit happened' . $e->getMessage()));
    exit;
}

$stmt = $conn->prepare("SELECT price_1 FROM table WHERE id = ?");
$stmt->execute(array($_GET['id']));
$result = $stmt->fetch(PDO::FETCH_ASSOC);

if($result === false){
    trigger_error('Query failed: ' . $conn->errorInfo());
    echo json_encode(array('success' => false, 'price_1' => '', 'message' => 'shit happened'));
    exit;
} else {
    echo json_encode(array('success' => true, 'price_1' => $result['price_1'], 'message' => ''));
    exit;
}

函数getPrice(id){
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=函数(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
var jsonObj=JSON.parse(xmlhttp.responseText);
if(jsonObj.success==true){
document.getElementById(“price_1”).value=jsonObj.price_1;
}否则{
document.getElementById(“price_1”).innerHTML=jsonObj.message;
}
}
};
open(“GET”、“ajax.php?id=“+id,true”);
xmlhttp.send();
}
获得报价
项目:

请选择:
尺寸:
请选择: 尺码1 尺码2 尺寸3
双重:
请选择: 对 不

总价: &欧元;


我会使用jQuery和AJAX

如果数据没有那么大,我会在页面加载上执行一个ajax请求(以防止用户在ajax调用上等待太多时间),并将结果存储到javascript全局/对象中

如果页面根本不需要刷新,而数据是“实时”的,那么等待时间可能会减少,但当用户选择一个选项时,您只需要启动一个ajax调用

您可以使用与此类似的结构:

//bind event of select changing to a funciton that fires off the ajax
//the below avoids having to attach/unattach evenmt handlers on any dynamic elements
var body = jQuery("body");
body.on("change","#selectID",updatePriceFunction);

function updatePriceFunction() {
    loader.show();//unhide the loading animation 
    var optionChosen = jQuery("#selectID").find("option:selected").val();//this assumes the options have values that are identifies for that option to be sent to the ajaxEndpoint
      var payload = {selectedOption: optionChosen, otherData: otherValueNeeded}; //makes a javascript object with values to be sent to fetch the price
      jQuery.ajax({
          type: "POST",
          url: urlToAjaxEndpoint,//string
          data: payload,
          dataType: "json",
          traditional: true,
          success: getDataSuccess,
          error: ajaxErrorHandling,
          complete: function() {loader.hide();}//always hide the loading animation, even if ajax fails
      });

      //methods seperated (not inline in the above ajax call) as to allow for reuse

      function getDataSuccess(data){//data is the response form the server, parsed using jQuery JSON if the ajaxEndpoint server said the response type was JSON
        if(data.result == true) {
            //find the table area you wnat to update, and use the new value
            //data.result .....
        } else {
            //server returned value indicating operation was successful, such as if the combo was invalid or not, etc
            //data.message ....
        }
      }

      function ajaxErrorHandling(jqXHR, textStatus, errorThrown){//jqXHR is the jquery xml html request object
            //ajax error connecting to endpoint / exception on response parsing
            var details = JSON.stringify(jqXHR, null, 4);
            console.error("Exception: "+errorThrown+" - Status: "+textStatus + " - XMLHTTPRequest:" + details);
            showAlertMessage("An error occurred");
      }
}

//this assumes the server returns a json object of the form:
//[
//  error: true/false,
//  message: "",
//  result: object
//]

//whatever the endpoint uses, you'll likely need to parse the payload object, and then create a json response
//be careful of special characters on the endpoint, as they can be "escaped" in the raw json and will throw a parse exception
这应该足以让你走上正确的道路。
注:jQuery不是必需的,但它使它变得容易多了。

如果您能提供到目前为止您所做的代码片段,那么就更容易理解您想要实现的目标,因为它现在没有意义。
//bind event of select changing to a funciton that fires off the ajax
//the below avoids having to attach/unattach evenmt handlers on any dynamic elements
var body = jQuery("body");
body.on("change","#selectID",updatePriceFunction);

function updatePriceFunction() {
    loader.show();//unhide the loading animation 
    var optionChosen = jQuery("#selectID").find("option:selected").val();//this assumes the options have values that are identifies for that option to be sent to the ajaxEndpoint
      var payload = {selectedOption: optionChosen, otherData: otherValueNeeded}; //makes a javascript object with values to be sent to fetch the price
      jQuery.ajax({
          type: "POST",
          url: urlToAjaxEndpoint,//string
          data: payload,
          dataType: "json",
          traditional: true,
          success: getDataSuccess,
          error: ajaxErrorHandling,
          complete: function() {loader.hide();}//always hide the loading animation, even if ajax fails
      });

      //methods seperated (not inline in the above ajax call) as to allow for reuse

      function getDataSuccess(data){//data is the response form the server, parsed using jQuery JSON if the ajaxEndpoint server said the response type was JSON
        if(data.result == true) {
            //find the table area you wnat to update, and use the new value
            //data.result .....
        } else {
            //server returned value indicating operation was successful, such as if the combo was invalid or not, etc
            //data.message ....
        }
      }

      function ajaxErrorHandling(jqXHR, textStatus, errorThrown){//jqXHR is the jquery xml html request object
            //ajax error connecting to endpoint / exception on response parsing
            var details = JSON.stringify(jqXHR, null, 4);
            console.error("Exception: "+errorThrown+" - Status: "+textStatus + " - XMLHTTPRequest:" + details);
            showAlertMessage("An error occurred");
      }
}

//this assumes the server returns a json object of the form:
//[
//  error: true/false,
//  message: "",
//  result: object
//]

//whatever the endpoint uses, you'll likely need to parse the payload object, and then create a json response
//be careful of special characters on the endpoint, as they can be "escaped" in the raw json and will throw a parse exception