从基于selectfield的数据库中获取结果

时间:2016-01-08 14:08:27

标签: javascript php ajax xajax

我一直在尝试创建一个页面,我可以选择一个客户,并从数据库中获取相应的客户详细信息。 看起来应该是这样的:

<select id="select_customer">   
  <option value='1'>customer 1</option>
  <option value='1'>customer 2</option> 
</select>

public function getCustomerDetails($customerId) {
    if(isset($customerId)) {
        $customer = DB::getInstance()->query("select * from customers");
        foreach($customer->results() as $customer) {
            $str = "<li>{$customer->name}</li>";
            $str .= "<li>{$customer->name_contactperson}</li>";
            $str .= "<li>{$customer->email}</li>";
            $str .= "<li>{$customer->address} {$customer->house_number}</li>";
            $str .= "<li>{$customer->postalcode}</li>";
            $str .= "<li>{$customer->city}</li>";
            $str .= "<li>{$customer->country}</li>";
        }

        return $str;
    } 
    return false;
}

我现在要做的是从select_customer中获取值,使用ajax将其发布到getCustomerDetails方法,并在没有页面重新加载的情况下获取相应的详细信息。 我试着让它与ajax和xAjax一起工作,但我还没法开始工作。

我试过了:

<?php include 'xajaxAIO.inc.php'; 
$xajax = new xajax(); 
$xajax->register(XAJAX_FUNCTION, 'getCustomers'); 
$xajax->processRequest(); ?> 
<input type="button" onclick="xajax_getCustomerDetails(1);" value="Click Me" />

我试过的另一件事是:

<script>
document.getElementById('select_customer').addEventListener('change', function() {
    var $userId = this.value;
    $.ajax({
        type: "POST",
        url: "classes/invoice.php",
        data: "getCustomerDetails("+$userId+")"
    })
});
</script>

我在控制台中没有收到任何错误消息,但似乎请求的函数没有执行。

有谁能告诉我它是如何让它发挥作用的?

提前致谢!

2 个答案:

答案 0 :(得分:1)

我建议只发送$ userId,然后在invoice.php页面中调用getCustomerDetails($ userId)。

$.ajax({
    type: "GET",
    url: "classes/invoice.php",
    data: $userId
  })
});

OR

$.ajax({
    type: "GET",
    url: "classes/invoice.php&function=getCustomerDetails&userId="+$userId
    dataType: "json", //Dont need this if youre returning a string
    success: function(result) {
        alert(result);
    }
  })
});

然后在发票页面中,您可以使用$ _GET变量调用该函数,如下所示:

 $response = 'error;
 if($_GET['function'] == 'getCustomerDetails'){
      if(!empty($_GET['userId'])){
           $_GET['userId'] = 0;
       }
       $userID = $_GET['userId'];
       $response = getCustomerDetails($userID);
 }
die(json_encode($response)); //for array
die($response); //for a string

答案 1 :(得分:0)

If you use xajax framework... you need register the new function...

<?php include 'xajaxAIO.inc.php'; 
$xajax = new xajax(); 
$xajax->register(XAJAX_FUNCTION, 'getCustomers');
$xajax->register(XAJAX_FUNCTION, 'getCustomerDetails'); 
$xajax->processRequest(); ?> 
<input type="button" onclick="xajax_getCustomerDetails(1);" value="Click Me" />

<?php function getCustomerDetails($id){
    ///////////////////////////////////////////////
    ///// And use framework xajax to response /////
    ///////////////////////////////////////////////
}?>