使用 jquery 和 PHP 从 MySQL 加载数据


load data from mysql with jquery and php

我有一个下拉列表(ddlAccount(,我可以从中选择一个项目并在测试中执行数据库查询.php以检索相应的数据,然后输出带有返回数据的输入元素。

这是我的javascript代码:

function load1(){
$('#divAccountNum').load('test.php?accountInfo=' + document.getElementById('ddlAccount').value , '' ,function() {
alert('Load was performed.')}); 
}

当我更改下拉列表项时调用 load1 函数,它获取所选选项的值并将其发送到测试.php在名为"accountInfo"的参数中。

我的网页:

  <select name="ddlAccount" id="ddlAccount" onchange="load1();">
    <option value="1"> Account1</option>
    <option value="2"> Account2</option>
    <option value="3"> Account3</option>
  </select>
  <div id="divAccountNum" >
  </div>

并测试.php :

if($_GET['accountInfo'])
{
    $account = $accountDAO->load($_GET['accountInfo']); //mysql query
        //print an input holding account number as its value
    echo "<input type='text' name='txtAccountNum' id='txtAccountNum' value='".$account->accountnumber."'/>"; 
}

问题是当我选择一个选项时没有任何反应(div (divAccountNum(中没有任何内容(有什么建议吗?提前谢谢。

编辑:我使用了@thecodeparadox的代码并且它有效,我找到了我在下面的评论中提到的问题的解决方案,即从下拉列表中选择一个项目时,它会显示输入元素中的值并再次加载表单。解决方案在于:jQuery Ajax 返回整个页面 所以我的jquery代码现在看起来像:

$(document).ready(function(){
  $('#ddlAccount').on('change', function() {  
$.get('testJquery.php?accountInfo=' + $(this).val(), function(accountNum) {
    //console.log(accountNum);
    $('input#txtAccountNum').val(accountNum);
   });
});

和测试Jquery.php:

if($_GET['accountInfo'])
{
    $account = $accountDAO->load($_GET['accountInfo']);
    $accountNum = $account->accountnumber;
    echo $accountNum;
}

最后,我在divAccountNum 中添加了 id="txtAccountNum" 的输入元素

虽然您没有提供有关问题的足够信息,但您可以尝试以下操作:

function load1(){
  $('#ddlAccount').on('change', function() {  
    $.get('test.php?accountInfo=' + $(this).val(), function(response) {
       $('div#divAccountNum').html(response);
    }, 'html');
  });
}

注意:

  1. 下拉列表更改时触发$('#ddlAccount').on('change',
  2. $.get('test.php?accountInfo=' + $(this).val()..test.php发送 get(ajax( 请求,并从下拉列表中选择值
  3. 参数response 在第二个参数回调函数中$.get()是来自服务器的响应
  4. 'html'作为您返回的数据类型的$.get()的第三个参数,因为您返回一个 html,因此它是html的。

欲了解更多信息,请阅读:

更改((

$.get((

要从选择输入中获取选定的选项值,请使用:

$('#ddlAccount option:selected').val()