JQuery帖子没有处理动态jQuery元素

时间:2022-11-28 16:33:20

NOTE: This question is a split from the post: jQuery not working on elements created by jQuery

注意:这个问题是从帖子中分离出来的:jQuery没有处理由jQuery创建的元素

I am dynamically adding list items to a list in jQuery through an ajax call that is called every second.

我通过每秒调用的ajax调用动态地将列表项添加到jQuery中的列表中。

Below is the code for the ajax call.

下面是ajax调用的代码。

$.ajax({
    url: 'php/update_group_list.php',
    data: '', 
    dataType: 'json',
    success: function(data) {
        var id = data.instructor_id;
            group_cnt = data.group_cnt,
            group_name = data.group_name,
            group_code = data.group_code;

            for (i = current_row; i < group_cnt; i++)
            {
                //setInterval(function() { $('#group-list-div').load('php/group_list.php'); }, 5000);

                $('#group-list').append("<li><a href='#' data-role='button' class='view-group-btns' id='"+group_code[i]+"' value='"+id+"' text='"+group_name[i]+"'>"+group_name[i]+"</a></li>");
                $('#delete-group-list').append("<fieldset data-role='controlgroup data-iconpos='right'>" +
                                                    "<input id='"+group_code[i]+i+"' value='"+group_code[i]+"' type='checkbox' name='groups[]'>" +
                                                    "<label for='"+group_code[i]+i+"'>"+group_name[i]+"</label>" +
                                                "</fieldset>");
            }

            current_row = i; 

            $('#group-list').listview('refresh');
            $('#delete-group-list').trigger('create');
    }
});

when I try to send the form data for the checkboxes (referencing line $('#delete-group-list').blah...blah in the ajax call code above) the post returns the error unexpected token <

当我尝试发送复选框的表单数据时(在上面的ajax调用代码中引用行$('#delete-group-list')。blah ... blah)帖子返回错误意外令牌<

What am I doing wrong? I think the two problems are related as I am creating the list items that are used dynamically.

我究竟做错了什么?我认为这两个问题是相关的,因为我正在创建动态使用的列表项。


Here is extra code relating to the problem

这是与问题相关的额外代码

HTML:

<form id='delete-group-form' action='php/delete_groups.php' method='post'>
    <h3 style='text-align: center;'>Check the Box Beside the Groups you Would Like to Delete </h3>
    <div style='margin-top: 20px;'></div>
        <div id='delete-group-list'>
        </div>
    <div style='margin-top: 20px;'></div>
    <input type='submit' id='delete-groups-btn' data-theme='b' value='Delete Groups(s)'>                    
</form>

JS Code

$('#delete-group-form').submit(function(e) 
{
    e.preventDefault();

    alert($('#delete-group-form').serialize());

    if ($('#delete-group-form').serialize() == "") 
    {
        alert('No groups selected to be deleted.')
        return false;
    }
    else 
        if ($('#delete-groups-form').serialize() == null) 
        {
            alert('No groups selected to be deleted.')
            return false;
        } 
        else 
        {
            $.post('php/delete_groups.php',$('#delete-groups-form').serialize()).done(function(data) 
            {
                obj = jQuery.parseJSON(data);


                var group_codes = obj.group_list;

                alert(group_codes);

                alert("The selected groups have been deleted");
                window.setTimeout(2000);
                return false;
            });
        }
    return false;
});

delete_groups.php

<?php 
    $group_codes = $_POST['groups'];    
    $items = array('group_list'=>$group_codes); //creating an array of data to be sent back to js file
    echo json_encode($items); //sending data back through json encoding
?>

I think the root of the SECOND problem is the line $group_codes = $_POST['groups']; specfically the $_POST['groups'] because when I replace it with $group_codes = 'test'; (just for debugging purposes) , the code works as expected.

我认为第二个问题的根源是行$ group_codes = $ _POST ['groups'];特别是$ _POST ['groups']因为当我用$ group_codes ='test'替换它时; (仅用于调试目的),代码按预期工作。

2 个解决方案

#1


0  

ok, previously i thought the mistake with the content type header of php file, still its there (you need to specify the header type to parse with jQuery JSON). But found one more mistake which i suppose the cause of the problem.

好吧,以前我认为php文件的内容类型标题的错误仍然存​​在(你需要指定用jQuery JSON解析的头类型)。但又发现了一个错误,我认为问题的原因。

<form id='delete-group-form' action='php/delete_groups.php' method='post'>

and the form you wish to serialize is

你希望序列化的形式是

$('#delete-groups-form').serialize()

You can see the difference in IDs. This will return an empty object, where in php file it expects the index called groups which never exists. Therefore it'll return an undefined index error as an html content type which starts with <html>, with that JSON parser return an error with unexpected token <

您可以看到ID的差异。这将返回一个空对象,在php文件中它需要一个从不存在的名为groups的索引。因此,它将返回一个未定义的索引错误作为以开头的html内容类型,该JSON解析器返回带有意外令牌的错误<

Hope this helps

希望这可以帮助

#2


0  

When you call $_POST['groups']; (in your delete_groups.php) it looks for the content sent from the form element with an attribute name="groups", but your delete-group-form doesn't have any such element.

当你拨打$ _POST ['groups']时; (在你的delete_groups.php中)它查找从表单元素发送的具有属性name =“groups”的内容,但是你的delete-group-form没有任何这样的元素。

The "error unexpected token <" message may be from a separate issue. Validating your HTML might reveal the issue.

“错误意外令牌<”消息可能来自单独的问题。验证HTML可能会揭示问题。

Also, I'm not entirely clear on why you're using two separate functions (the $.post in your JS and the $.ajax). Unless there's something else going on that I can't see from the code you've posted, you could simplify it considerably by just using one call to ajax. Put that one call inside the $('#delete-group-form').submit(function(e) in place of the $.post, and pass your groups variable using the ajax call's data parameter. Modify delete_groups.php to return the necessary information (currently returned from update_group_list.php) to update the display on your page.

另外,我并不完全清楚你为什么要使用两个独立的函数(JS中的$ .post和$ .ajax)。除非发生了其他事情,否则我无法从您发布的代码中看到,只需使用一次调用ajax就可以大大简化它。将一个调用放入$('#delete-group-form')。submit(function(e)代替$ .post,并使用ajax调用的数据参数传递groups变量。修改delete_groups.php返回必要的信息(当前从update_group_list.php返回)以更新页面上的显示。

#1


0  

ok, previously i thought the mistake with the content type header of php file, still its there (you need to specify the header type to parse with jQuery JSON). But found one more mistake which i suppose the cause of the problem.

好吧,以前我认为php文件的内容类型标题的错误仍然存​​在(你需要指定用jQuery JSON解析的头类型)。但又发现了一个错误,我认为问题的原因。

<form id='delete-group-form' action='php/delete_groups.php' method='post'>

and the form you wish to serialize is

你希望序列化的形式是

$('#delete-groups-form').serialize()

You can see the difference in IDs. This will return an empty object, where in php file it expects the index called groups which never exists. Therefore it'll return an undefined index error as an html content type which starts with <html>, with that JSON parser return an error with unexpected token <

您可以看到ID的差异。这将返回一个空对象,在php文件中它需要一个从不存在的名为groups的索引。因此,它将返回一个未定义的索引错误作为以开头的html内容类型,该JSON解析器返回带有意外令牌的错误<

Hope this helps

希望这可以帮助

#2


0  

When you call $_POST['groups']; (in your delete_groups.php) it looks for the content sent from the form element with an attribute name="groups", but your delete-group-form doesn't have any such element.

当你拨打$ _POST ['groups']时; (在你的delete_groups.php中)它查找从表单元素发送的具有属性name =“groups”的内容,但是你的delete-group-form没有任何这样的元素。

The "error unexpected token <" message may be from a separate issue. Validating your HTML might reveal the issue.

“错误意外令牌<”消息可能来自单独的问题。验证HTML可能会揭示问题。

Also, I'm not entirely clear on why you're using two separate functions (the $.post in your JS and the $.ajax). Unless there's something else going on that I can't see from the code you've posted, you could simplify it considerably by just using one call to ajax. Put that one call inside the $('#delete-group-form').submit(function(e) in place of the $.post, and pass your groups variable using the ajax call's data parameter. Modify delete_groups.php to return the necessary information (currently returned from update_group_list.php) to update the display on your page.

另外,我并不完全清楚你为什么要使用两个独立的函数(JS中的$ .post和$ .ajax)。除非发生了其他事情,否则我无法从您发布的代码中看到,只需使用一次调用ajax就可以大大简化它。将一个调用放入$('#delete-group-form')。submit(function(e)代替$ .post,并使用ajax调用的数据参数传递groups变量。修改delete_groups.php返回必要的信息(当前从update_group_list.php返回)以更新页面上的显示。