在我的网页上,当用户点击一个单词时,它应该显示该单词的定义。当用户单击该单词时,它会将单词变量发送到连接到牛津词典 API 的 php 文件,并查询该单词的定义,然后将该定义返回到网页。问题是当我试图通过ajax将单词变量传递给php文件时,它似乎不起作用。我正在使用php包装器来使用api,当我手动设置单词查询时没有问题。我能够连接到api并检索定义和所有内容,因此我认为问题在于ajax部分。在这次作业之前,我从未使用过jquery,ajax或php。我不确定我做错了什么。请帮忙!
我的 JS 文件
function getSelectedText(){
var selectedText = '';
if (window.getSelection)
selectedText = window.getSelection();
return selectedText;
}
// Retrieve definition
$(document).ready(function()
{
var selected_text = getSelectedText();
$('#selectable').on("dblclick", function () {
$('.selection').text(selected_text);
$('.is-selected').text(getSelectedText() !== '');
});
$.ajax({
url: "dictionary.php", // php file path
method: "POST", // send data method
data: {"selected_text": selected_text}, // data to send {name: value}
success: function(data){
alert(data);
} // response of ajax
});
});
我的电脑文件
$selected_text = $_POST['selected_text'];
echo $selected_text;
$dictionary->queryWord($selected_text);
$dictionary->setResult(0);
/* Get results from dictionary class */
echo "<h1>Dictionary Class Results - ".$dictionary->getWord()."</h1>";
echo "<b>Word:</b> ".$dictionary->getWord();
echo "<br><b>Definition:</b> ".$dictionary->getDefinition();
echo "<br><b>Short Definition:</b> ".$dictionary->getShortDefinition();
echo "<br><b>Example:</b> ".$dictionary->getExample();
/* Displays the current result set */
echo "<br></br>Using result set: <b>".$dictionary->selected_result."</b>";
?>
POPMUISE