簡體   English   中英

Jquery.ajax使用php從html加載數據

[英]Jquery.ajax load data from html using php

我在使用php從html加載輸入字段時遇到一些問題。 我正在使用jQuery Ajax $.post函數將輸入的數據發送到php文件,以便從數據庫中進行查詢。

我已經修復了代碼。 下面的代碼運行完美。

這是我主頁上的html

<input class="detail" maxlength="60" name="detail" placeholder="Type to search">
<button class="searchbtn" name="search">Search</button>

這是jQuery Ajax的一部分

$(".searchbtn").click(function(e) {
    makeAjaxRequest();  
});

function makeAjaxRequest(){
var input = $(".detail").val(); 
$.post("search.php",{detail:input},function(data,status){
        $('#resultTable tbody').html(data);

});

然后最后一部分是php文件(search.php)

if (isset($_POST['detail'])) {
    $data = $_POST['detail'];

    $query = "SELECT * FROM products WHERE ".%data; 
$result = $conn->query($query) or trigger_error($mysqli->error."[$sql]");

while($row = $result->fetch_assoc()){
    $rows[] = $row;
}
}

現在,它運行良好。 感謝您的回答。

當前,您只是發送沒有鍵/值的字符串。 您需要將鍵/值對作為數據參數(字符串或對象)發送(對象比較安全,因為它會自動進行urlencoded)

$.post("search.php",{detail:input},function(data,status){

你可以試試看。

function makeAjaxRequest(){
    var input = $(".detail").val(); 
    $.post("search.php",
        {detail: input},
        function(data,status){
            $('#resultTable tbody').html(data);

    });
}

您正在服務器端頁面上提取$_POST['detail'] ,但在客戶端發送時,您將像這樣發送$.post("search.php",input

數據應作為PlainObject或字符串發送。 我的意思是,每個POST數據都應有一些索引才能在另一端被引用。

由於您要使用索引detail進行提取,因此請添加以下內容的detail

$.post("search.php",{detail:input},function(data,status){

參見: jQuery:$ .post()

暫無
暫無

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

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