亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 AJAX 將數據從 jquery 發送到 php 文件,然后再發送回

使用 AJAX 將數據從 jquery 發送到 php 文件,然后再發送回

PHP
烙印99 2022-09-24 17:12:58
在我的網頁上,當用戶點擊一個單詞時,它應該顯示該單詞的定義。當用戶單擊該單詞時,它會將單詞變量發送到連接到牛津詞典 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>";?> 
查看完整描述

1 回答

?
POPMUISE

TA貢獻1765條經驗 獲得超5個贊

首先,函數實際上應該返回選定的文本getSelectedText


function getSelectedText(){

    var selectedText = '';

    if (window.getSelection) selectedText = window.getSelection().toString();

    return selectedText;

    // 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 () {

    // Marked contants since it won't change

    const selected_text = getSelectedText();

    // Make sure you check if the string is not empty before you do the request too

    if(selected_text.trim().length > 0)

    // Then do the request and process the output

    $.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);

        }

    });

});


查看完整回答
反對 回復 2022-09-24
  • 1 回答
  • 0 關注
  • 77 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號