2010-10-06 97 views
0

我有一個「小」的問題,因爲我不知道什麼是處理AJAX jQuery數據庫請求的最佳方式?處理Ajax jQuery數據庫查詢的最佳實踐?

到目前爲止,我已經做到了這種方式: 對於以往(單)數據庫請求我創建了一個新的PHP文件,如:

newbill.php 
newcosumer.php 
listallbills.php 
updatecostumer.php 

..和等,並通過拉數據:

$.ajax({ 
type: "POST", 
    url: "ajax/newbill.php", 
    data: "..." 
    success: function(msg){  
    ... 
    } 
}); 

..我不喜歡所有的.php文件只有一個!數據庫請求!?
必須有更好的方式來處理這個?

+0

你有什麼特別的問題? – 2010-10-06 12:24:19

+0

這不是一個jQuery的問題。這實際上是關於服務器端模式和實現。如果您將PHP標籤添加到您的帖子中,您可能會得到更好的答案。 – Gregg 2010-10-06 13:02:13

回答

2

我會這樣做。

爲每個實體創建一個php文件(例如:consumerajax.php,billajax.php等),然後爲每個數據庫查詢分別設置函數。當從javascript傳遞一個querystring變量來確定哪個在AJAX服務器頁面

防爆要執行的功能:在consumerajax.php

<?php 

    $mode= $_GET["mode"] ; 
    if($mode=="getconsumerdet") 
    { 
     $consumerId=$_GET["cid"]; 
     GetConsumerDetails($consumerId) 
    } 
    else if($mode=="updateconsumer") 
    { 
     $consumerId=$_GET["cid"]; 
     $name=$_GET["name"]; 
     UpdateConsumerInfo($consumerId, $name) 
    } 

    function GetConsumerDetails($consumerId) 
    { 
     // execute query the table here and return the result from here 
     echo"Have the data and return" 
    } 
    function UpdateConsumerInfo($consumerId,$name) 
    { 
     //execute query to update 
    echo "updated"; 
    } 

?> 

,並從你的紙條調用,比如

$.ajax({ type: "POST", url: "ajax/consumerajax.php?mode=getconsumerdet&cid=34", data: "..." success: function(msg){ }); 

$.ajax({ type: "POST", url: "ajax/consumerajax.php?mode=updateconsumer&cid=34&name=shyju", data: "..." success: function(msg){ }); 
+0

thx,多數民衆贊成,我也在想這樣的事情(與這種助手變量= $模式),但認爲可能有更好的方法來解決的功能(或方法在一個類)直接以某種方式? – Don 2010-10-07 22:31:11

1

您可以創建一個名爲ie的文件。 dbrequest.php並傳遞參數,然後你從php讀取數據並向數據庫提出相應的請求。

但是,這取決於你在頁面內究竟做了什麼,如果它很容易維護在一個單一的文件..

+0

我的想法是有一個數據庫查詢的Datamanager類,但也許一個普通的腳本文件與功能將(如Shyju所示)?爲什麼它很複雜,當它可以是簡單的:) – Don 2010-10-07 22:35:34