簡體   English   中英

將頁面內容從單獨的頁面獲取到表單提交的div中,而無需重新加載當前頁面

[英]Get page content from separate page into div on form submit without reloading current page

我正在嘗試從另一個頁面獲取數據並將其響應和內容加載到我擁有表單的頁面中的div中,而不重新加載表單頁面。 當我嘗試這段代碼時,它將刷新頁面,並且不會獲取結果。

我擁有表單的當前jquery代碼-form.php:

<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-latest.js'></script>
<script>
$('#skipreload').submit(function() { // catch the form's submit event
    $.ajax({ // create an AJAX call...
        data: $(this).serialize(), // get the form data
        type: $(this).attr('GET'), // GET or POST
        url: $(this).attr('dbresults.php'), // the file to call
        success: function(response) { // on success..
            $('#form_output').html(response); // update the DIV
        }
    });
    return false; // cancel original event to prevent form submitting
});
</script>
</head>
<body>

<form id="skipreload" method="GET" action="form.php">
<input type="text" name="id">
<input type="submit" value="Get results">
</form>

<div id="form_output">
<!--Show the result here from dbresults.php-->
</div>

</body>
</html>

我要從中獲取結果的頁面中的代碼-dbresults.php:

include("dbsettings.php");

$id = "";

if ($_GET)
{
$id = $_GET['id'];

    $sql = "SELECT Results FROM Table WHERE id = '$id';";
    $result = mysql_query($sql);

    while($row = mysql_fetch_array($result))
    {
        echo $row["Results"]";
    }
}

當我在form.php中提交表單時,頁面重新加載而沒有將結果從getresults.php放入div“ #form_output”-為​​什么它不起作用?

$.ajax調用中有一些錯誤。 如果要使用表單上當前的值,請僅使用.attr() ,即使這樣,也需要按屬性名稱而不是屬性value進行選擇

更改為:

$.ajax({ // create an AJAX call...
    data: $(this).serialize(), // get the form data
    type: 'GET', // GET or POST
    url: 'dbresults.php', // the file to call
    success: function(response) { // on success..
        $('#form_output').html(response); // update the DIV
    }
});

您也可以使用$.get完成相同的任務

$.get('dbresults.php', $(this).serialize(), function(response) {
    $('#form_output').html(response);
});

另外,您需要將代碼包裝在.ready()塊中:

$(document).ready(function() { // alternatively $(function() {
    [...]
});

沒有屬性GET ,它是method的值,沒有屬性'dbresults.php'action屬性的值。

另外,您的代碼在表單存在之前被調用

嘗試:

$(function(){ // wait until documented is ready so element exists

    $('#skipreload').submit(function() { // catch the form's submit event
        $.ajax({ // create an AJAX call...
            data: $(this).serialize(), // get the form data
            type: $(this).attr('method'), // GET or POST
            url: $(this).attr('action'), // the file to call
            success: function(response) { // on success..
                $('#form_output').html(response); // update the DIV
            }
        });
        return false; // cancel original event to prevent form submitting
    });

});

暫無
暫無

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

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