在 jQuery UI 自动完成结果点击时通过 POST 传递值

Passing value through POST on jQuery UI autocomplete result click

我正在尝试使用 POST 将所选项目的 ID 值传递到 search.php 文件。如果我使用 GET 它工作正常但如果我使用 POST.

则不起作用

这是我的代码:

$( function() {
    $( ".search" ).autocomplete({
        source: function( request, response ) {
            $.ajax({
                url: "/_inc/autocomplete.php",
                dataType: "json",
                data: {
                    q: request.term
                },
                success: function( data ) {
                    response( data );
                    console.log(data);
                }
            });
        },
        minLength: 2,
        select: function( event, ui ) {
            //alert('selected: ' + ui.item.name);
            var id = ui.item.id;
            $.post("/search.php", {"id": id});
            $(location).attr('href', '/search.php');
        }
    }).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
        if(item.label == 'No Match Found'){
            return $( "<li>" )
            .data( "item.autocomplete", item )
            .append( item.value )
            .appendTo( ul )
            .css("cursor", "default");
        } else {
            return $( "<li>" )
            .data( "item.autocomplete", item )
            .append( ("<a>" + item.id + " - " + item.name + "</a>") )
            .appendTo( ul );
        }
    };
});

从数据库中提取数据源并使用 PHP 转换为 JSON。

在完成上面评论中建议的问答后,我设法让它工作了。 jQuery 自动完成使用 GET 传递变量,因此我不得不使用 AJAX 调用来传递变量,而不是使用 html 数据类型。这是代码:

var id = ui.item.id;

$.ajax({
    url: "/search.php",
    type: "POST",
    dataType: 'html',
    data: { id: id },
    success: function(data){
        alert(data);
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert("ERROR:" + xhr.responseText+" - "+thrownError);
    }
});