gpt4 book ai didi

javascript - 尝试使其动态时,jQuery AJAX 自动完成功能不起作用

转载 作者:行者123 更新时间:2023-11-30 23:56:28 25 4
gpt4 key购买 nike

如果有硬编码数据输入其中,我的自动完成功能可以正常工作。我的 PHP 返回 JSON 结果。我不确定我哪里出错了。

HTML

<div class="form-group bgcolor">
<label for="send_to">Direct to: </label><input type="text" name="send_to" id="send_to" class="form-control send_to typeahead" placeholder="Leave blank normally">
</div>

Jquery

        $('.typeahead').typeahead({
source: {
groupName: {
ajax({
url: 'scripts/order_messaging.php',
method: 'POST',
data: JSON.stringify({action: 'autocomplete_to_user', query:query}),
contentType: 'application/json',
dataType: 'json',
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
},
},
debug: true
});

PHP

//autocomplete user name for user_to
if ( $_POST['action'] == 'autocomplete_to_user' ) {
$stmt = $pdo->prepare('select * from login where username like :query');
$stmt->bindValue('query', '%'.$_POST['query'].'%');
$stmt->execute();
$result = array();
while($user_name = $stmt->fetch(PDO::FETCH_OBJ)) {
array_push($result, $user_name->username);
}
echo json_encode($result);
}

我认为这是我的 jQuery 中的这一行: data: {action: 'autocomplete_to_user', query:query}, 也许我有语法问题。

最佳答案

根据jQuery Ajax Documentation , dataType: 'json' 将响应计算为 JSON 并返回 JavaScript 对象。

在将数据发送到 PHP 之前,您需要使用 JSON.stringify({action: 'autocomplete_to_user', query:query}) 对数据进行字符串化。此外,您还需要添加 header Content-Type: 'application/json' 告诉您请求数据是 JSON 的 PHP 代码。您可以通过在 Ajax 设置中添加 contentType: 'application/json' 来实现此目的。

您的最终 jQuery 代码将如下所示:

$('.typeahead').typeahead({
source: function(query, result)
{
$.ajax({
url: 'scripts/order_messaging.php',
method: 'POST',
data: JSON.stringify({action: 'autocomplete_to_user', query:query}),
contentType: 'application/json',
dataType: 'json',
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});

引用jQuery Ajax Documentation了解模式详细信息。希望这有帮助!

编辑:

您需要更新 PHP 代码才能读取 JSON。请引用这个link 。您的 PHP 代码应如下所示:

<?php
// Read the input stream
$body = file_get_contents("php://input");

// Decode the JSON object
$object = json_decode($body, true);
//autocomplete user name for user_to
if ( $object ['action'] == 'autocomplete_to_user' ) {
$stmt = $pdo->prepare('select * from login where username like :query');
$stmt->bindValue('query', '%'.$object['query'].'%');
$stmt->execute();
$result = array();
while($user_name = $stmt->fetch(PDO::FETCH_OBJ)) {
array_push($result, $user_name->username);
}
echo json_encode($result);
}
?>

关于javascript - 尝试使其动态时,jQuery AJAX 自动完成功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61018773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com