2017-02-10 102 views
0

首先,让我说我刚开始学习Web开发的基本知识 - HTML,CSS,JavaScript和PHP。带有多个选择框条件的Ajax请求

我试图实现与数据库查询的网页,并遇到了一些dificulties:

如果有人能见识一下哪种方式进行,将不胜感激。

我不想你写整个代码但对我来说是给我一些提示和线索。

我有一个表,Id,项目,price1,price2和price3。

经过大量搜索后,我设法将所有项目dynamicaly加载到选择列表中,并根据使用ajax调用选择的项目在on事件中显示(price1)on on change事件。

现在我需要更新基于其他两个选择列表这个价格格:一个用3个值(A,B,C),另一种用(是或否)。

如果选择列表2是(a)和选择列表3(是)要被显示的价格(price2);如果选择清单2是(b)并且选择清单3是(是),则要显示的价格是(price3),并且如果选择清单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; 
} 

的index.php

<?php 
Connection Variables 
try { 
    $conn = new PDO("mysql:host=$servername;dbname=test;charset=UTF8", $username, $password); 
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
} catch (PDOException $e) { 
    trigger_error("Connection failed: " . $e->getMessage()); 
} 
$query = "SELECT `id`, `items`, `price_1` FROM `table`"; 
$rows = $conn->query($query)->fetchAll(PDO::FETCH_ASSOC); 
?> 
<!DOCTYPE html> 
<html> 
    <head> 

     <script> 
      function getPrice(id){ 
       var xmlhttp = new XMLHttpRequest(); 
       xmlhttp.onreadystatechange = function() { 
        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; 
         }else{ 
          document.getElementById("price_1").innerHTML = jsonObj.message; 
         } 
        } 
       }; 
       xmlhttp.open("GET", "ajax.php?id=" + id, true); 
       xmlhttp.send(); 
      } 
     </script> 
    </head> 
<body> 



<div> 

<h3>GET A QUOTE</h3> 



    Item: 
    <br> 
    <select name="price" id="priceSelect" onchange="getPrice(this.value)"> 
     <option>Please select:</option> 
    <?php foreach ($rows as $row): ?> 
     <option value="<?= $row['id'] ?>"><?= $row['items'] ?></option> 
    <?php endforeach; ?> 
    </select> 
    <br> 

    size: 
    <br> 
<select name="price" id="sizeselectSelect" onchange="sizePrice(this.value)"> 
     <option>Please select:</option> 
     <option value="1">size1</option> 
     <option value="2">size2</option> 
     <option value="3">size3</option> 
    </select> 

<br> 
     double: 
     <br> 
     <select name="bouble" id="doubleprice" onchange="lastprice(this.value)"> 
     <option>Please select:</option> 
     <option value="yes">Yes</option> 
     <option value="no">No</option> 
    </select> 
<br> 
<br> 
Total price: 

    <input type="text" name="price_1[]" value="" id="price_1">&euro; 
    <p id="error"></p> 


</body> 
</html> 
+0

如果你能提供什么你迄今所做使用代码片断它会更容易明白你想实现,因为它没有任何意义,现在是什么。 – kabirbaidhya

回答

0

我会使用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 

这应该足以让你开始正确的道路。 PS:jQuery不是必需的,但它使它更容易。