jQuery不显示返回的数据


AJAX jQuery doesn't display returned data

我有一个脚本来获取数据并将其加载到div中,代码工作良好,如果我不使用任何表单值,如果我不使用type="POST",则显示用户id列表,但它不起作用(没有结果,没有控制台错误消息)当我使用$_POST值:

HTML:

 <form name='newUser' id="searchForm" method="POST">
<input type="text" name="look_for" id="look_for">
<input type="text" name="lookage_from" id="age_from">
<input type="text" name="age_to" id="age_to">
</form>

fetchusers.php

$look_for = $_POST['look_for'];
$age_from = $_POST['age_from'];
$age_to = $_POST['age_to'];
$array = getProfilePicsList($look_for,$age_from,$age_to); //a function that select * from ...
echo json_encode($array);
jquery代码:

$("#searchForm").submit(function(event)
{
    $.ajax({
        type: 'POST',
        url: 'models/fetchUsers.php', //the script to call to get data
        dataType: 'json',             //data format
        success: function(data)       //on recieve of reply
        {
            $.each($(data), function(key, value) {
                $('#itemContainer').append(value.user_id);
            });
        }
    });
    return false;
});

在您的ajax请求中,您缺少data。只要加上这个:

data: $("#searchForm").serialize(),

例子:

$.ajax({
    type: 'POST',
    url: 'models/fetchUsers.php', //the script to call to get data
    dataType: 'json',             //data format
    data: $("#searchForm").serialize(),
    success: function(data)       //on recieve of reply
    {
        $.each($(data), function(key, value) {
            $('#itemContainer').append(value.user_id);
        });
    }
});

如果不使用data参数,则无法获取$_POST数组中的值。

参考:https://api.jquery.com/jquery.post/http://www.w3schools.com/ajax/ajax_xmlhttprequestrongend.asp