簡體   English   中英

將當前HTML文本框值從JavaScript傳遞到PHP,而無需重新加載頁面或寫入URL

[英]Pass current HTML textbox value from JavaScript to PHP without reloading the page or writing to the URL

該文件是index.php 它有一個文本框 ,有人可以在其中輸入字符。 Onkeyup,觸發了一個JavaScript函數,該函數調用search.php:

<input type="text" id="search" placeholder="filter items" onkeyup="return searchFunc()">

<script>
    function searchFunc() {
    var param = document.getElementById("search").value; //Current value in text box.
    getRequest(
        'snippets/search.php', //URL for the PHP file.
        drawOutput,  //Handle successful request.
        drawError    //Handle error.
    );
    return false;
    }

    //Handles drawing an error message.
    function drawError() {
    var container = document.getElementById('grid');
    container.innerHTML = 'Oops, there was an error!';
    }

    //Handles the response, adds the HTML.
    function drawOutput(responseText) {
    var container = document.getElementById('grid');
    container.innerHTML = responseText;
    }
    //Helper function for cross-browser request object.
    function getRequest(url, success, error) {
        var req = false;
        try{

        //Most browsers.
        req = new XMLHttpRequest();
        } catch (e){

        //Internet Explorer.
        try{
        req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {

        //Older versions.
        try{
        req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {
            return false;
            }
        }
    }

    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req.readyState == 4) {
            return req.status === 200 ? 
            success(req.responseText) : error(req.status);
        }
    }

    req.open("GET", url, true);
    req.setRequestHeader("Cache-Control", "no-cache"); //Prevents browser from caching the last response (This line and the next two.)
    req.setRequestHeader("Pragma", "no-cache");
    req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    req.send(null);
    return req;
    }
    </script>

    <div id="grid">
    Type something into the search field!

上面的代碼運行完美,並且主要由我在這個論壇上搜索了幾個小時而組成。

接下來,讓我們進入search.php 該文件的目的(最終)是在MySQL數據庫中搜索帶有“ title”的行,這些行與用戶開始在搜索框中輸入的內容匹配,並在每次按鍵后進一步完善結果。 但出於測試目的, 我要顯示的只是搜索框中的當前值

<?php
echo $_GET['param'];
?>

當我開始在搜索框中輸入內容時,我得到: "Notice: Undefined index: param in C:\\xampp\\htdocs\\testsite\\snippets\\search.php on line 22" 我肯定使用$ _GET錯誤。 我見過無數線程表明可以通過將參數附加到URL上來實現此目的,例如“?value =” + param,然后從PHP引用它,但是我沒有寫URL-URL不變在整個過程中都沒有。 有人可以指出我正確的方向嗎?

您可以向URL添加強查詢

getRequest(
    'snippets/search.php?param='+param,  //URL for the PHP file.
    drawOutput,  //Handle successful request.
    drawError    //Handle error.
);

如果您不想更改url,則可以在send()方法中傳遞parama。

    ....
     req.send('param='+param);

使用jQuery的AJAX

示例代碼:

  $.post("edit.php",
  {
      phpcontent: jscontent,
      phpid: jsid,
  },
  function(data, status){
      alert("Data: " + data + "\nStatus: " + status);
  });

然后,您可以使用PHP $_POST [ 'vars' ]

根據我的評論,這是使用jQuery和PHP的方法:

<input type="text" id="search" placeholder="filter items" />
<div id="grid"></div>

<script>
    // Store response into grid.
    function onSearchComplete(response) {
        $('#grid').html(response.html);
    }

    function onKeyUpSearch() {
        $.post(
            'search.php',
            {
                ts   : Date.now(), // Be very very sure we're not caching
                text : $('#search').val()
            }
        ).done(onSearchComplete);
    }

    $(function() {
        // Main
        $('#search').on('keyup', onKeyUpSearch);
    });
</script>

PHP方面:

$text = $_POST['text'];


$response = array(
    'status' => 'success', // This may come handy later on.
    'html'   => "<strong>OK! You typed {$text}.</strong>",
);
header('Content-Type: application/json;charset=utf-8');
die(json_encode($response));

更新:添加樣式文本

當然,只要使用jQuery函數.html()存儲,就可以添加任何類型的HTML並將其發送到JSON響應中。

如果要發送一些樣式不同的數據,則最好在客戶端構建它,只要它的結構已知即可。 例如我們返回

array(
    'status'  => 'success',
    'records' => array(
        0 => array( 'name' => 'John', 'surname' => 'Smith' , ... ),
        1 => array( 'name' => 'Jack', 'surname' => 'Evans' , ... ),
    )
)

並且我們使用jQuery在Javascript中對其進行處理:

    function onSearchComplete(response) {
        if (response.status != 'success') {
            alert('Error: ' + response.message);
            return;
        }
        // Empty the grid
        $('#grid').empty();
        var table = $('<table>').addClass('data-table');
        response.records.forEach(function(record) {
            // This function will be executed for every record
            var row = $('<tr>').addClass('data-row');
            Object.keys(record).forEach(function(key) {
                // key is "name", value is "John"
                var cell = $('<td>').text(record[key]);
                // Note that above I use .text(), not .html().
                // It's faster, but if the server sends "<em>Italics</em>"
                // I'll not see "Italics" in italics - I'll see an ugly
                // "&lt;em&gt;Italics&lt;/em&gt;".
                // To interpret HTML tags, use .html().

                row.append(cell);
            });
            table.append(row);
        });
        // Finally put the table in place.
        $('#grid').append(table);
    }

當然,您可以組裝服務器端的所有內容,然后像上面的原始答案一樣,在JSON內部發送HTML。 那也行。 但是,這樣一來,我們獲得的流量就更少了,雖然代碼編寫起來有些困難,但維護起來卻更容易。 通常,當您編寫一些內容然后不得不將其保留很長時間時,這就是方法。

如果HTML變得太復雜,那么也有相應的庫。 您可能會對Twig(PHP方面)和Handlebars(Javascript方面)感興趣。

如果要保留同一頁面,但需要與服務器交互,那么您要尋找的是AJAX ,這是純JavaScript的示例(無需jQuery):

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4)
    {
        if(xhttp.status == 200) 
        {
            //Success, HTTP response code 200
            alert(xhttp.responseText);
        }
        else
        {
            //Failure, HTTP response code different from 200
            alert("Error while executing the request");
        }
    }
};
xhttp.open("GET", "/path/of/search.php?parameter=parameterValue", true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.send();

在此示例中,客戶端在服務器上的以下路徑上調用search.php: /path/of/search.php xhttp.readyState == 4表示請求已完成(因此操作已完成), xhttp.status包含服務器返回的HTTP響應代碼xhttp.responseText您將擁有從服務器打印的所有內容(例如echo )。 您可以通過更改字符串"/path/of/search.php?parameter=parameterValue"來輕松操縱發送的參數,例如: "/path/of/search.php?parameter="+variable

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM