【问题标题】:Can I call jquery.ajax() with some other function?我可以用其他函数调用 jquery.ajax() 吗?
【发布时间】:2015-01-07 09:17:50
【问题描述】:

我正在使用 jQuery DataTables 插件,它有一个事件,点击按钮我们可以在表格中添加新行。
jQuery代码如下:

$(document).ready(function() {
var t = $('#example').DataTable();
var counter = 1;
$('#addRow').on( 'click', function () {
    t.row.add( [
         counter,
        '<select id="k'+counter+'" name="itemname'+counter+'" ><option>-------</option></select>' ,
        '<input id="itemrate" name="itemqty'+counter+'"  placeholder="Quantity"  type="text">',
        '<input id="itemrate" name="itemrate'+counter+'"  placeholder="Rate"  type="text">',
        '<input id="totalamt" name="totalamt'+counter+'"  placeholder="Total Amount"  type="text">'
                ] ).draw();
                counter++;
            }); 
    });

我想用jQuery.ajax()填充从MySQL数据库获取的数据,我的代码如下:

jQuery(document).ready(function(){
    jQuery('#k'+counter).click(function(){
        jQuery.ajax({
            url: 'getData.php',
            type:'POST',
            data:'form_data='+val,
            success:function(results){
                jQuery('#k'+counter).html(results);
            }
        });
    }); 
    });

getdata.php的代码如下:

<?php

mysql_connect('localhost','root','');
mysql_select_db('eroyalsum');

$sql = "SELECT ITEMCODE,ITEMNAME FROM itemmaster1";
$result = mysql_query($sql);

while($row = mysql_fetch_row($result))
{
    echo '<option value="'.$row[0].'" >'.$row[1].'</option>';
}

?>

最后,我的问题是当我将它编写为单独的函数时,它只能工作一次。当我添加其他行时它不起作用,当我在一个函数中编写 jQuery 的 .ajax() 时它不起作用...

【问题讨论】:

  • it not work 到底是什么意思?

标签: php jquery ajax jquery-datatables


【解决方案1】:

尝试更改您的选择器:

jQuery('#k'+counter).click(function(){
…

jQuery(document).on("change", "select[id^='k']", function(){
...

【讨论】:

    【解决方案2】:

    问题在于事件绑定。

    当您将事件绑定到 #k 元素时,新项目不会自动获取绑定到它的事件。

    你可以使用类似的东西:

    $('body').on('click','.new_elements',function(){ //dostuff});
    

    你可以在这里阅读更多关于它的信息

    Event binding on dynamically created elements?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 2012-10-31
      相关资源
      最近更新 更多