使用 AJAX 将数据从 jquery 发送到 php 文件,然后再发送回

在我的网页上,当用户点击一个单词时,它应该显示该单词的定义。当用户单击该单词时,它会将单词变量发送到连接到牛津词典 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>";


?> 


烙印99
浏览 64回答 1
1回答

POPMUISE

首先,函数实际上应该返回选定的文本getSelectedTextfunction getSelectedText(){&nbsp; &nbsp; var selectedText = '';&nbsp; &nbsp; if (window.getSelection) selectedText = window.getSelection().toString();&nbsp; &nbsp; return selectedText;&nbsp; &nbsp; // Or even better using ternary operator: return window.getSelection ? window.getSelection().toString() : '';}然后,正如不可思议的帽子所说,你应该纠正你处理事件的方式,可能如下,因为我通常使用获取API来实现这种目的:-// Only fire the ajax when user double click any text/selectables$('#selectable').on("dblclick", function () {&nbsp; &nbsp; // Marked contants since it won't change&nbsp; &nbsp; const selected_text = getSelectedText();&nbsp; &nbsp; // Make sure you check if the string is not empty before you do the request too&nbsp; &nbsp; if(selected_text.trim().length > 0)&nbsp; &nbsp; // Then do the request and process the output&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; url: "dictionary.php", // php file path&nbsp; &nbsp; &nbsp; &nbsp; method: "POST", // send data method&nbsp; &nbsp; &nbsp; &nbsp; data: {"selected_text": selected_text}, // data to send {name: value}&nbsp; &nbsp; &nbsp; &nbsp; success: function(data){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(data);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });});
打开App,查看更多内容
随时随地看视频慕课网APP