2012-10-18 39 views
1


時重新加載DIV我有一個簡單 FORM,一個 INPUT和一個提交按鈕。從那裏的數據將被髮送到 PHP腳本,該腳本將其發送到db,然後將其放入 DIV。 (與聰明)
沒有Ajax,它工作得很好,數據轉到數據庫,它會顯示等。但對於Ajax來說,它會更快,更輕量。與阿賈克斯只能提交表單

通常,提交會重新加載頁面或重定向到我定義的頁面。

但是有沒有辦法在提交之後重新加載DIV?

的HTML:

<div> <!-- THE DATA FROM THE FORM VIA PHP --> </div> 

<form id='foo'> 
<input type='text'> 
<input type='submit'> 
</form> 

了jQuery至今:

$('#foo').submit(function(event){ 
    $.ajax({ 
    url: 'index.html', 
    type: 'post, 
    data: $('#foo').serialize(), 
    success: function(response, textStatus, jqXHR){ 
     console.log('worked fine'); 
    }, 
    error: function(jqXHR, textStatus, errorThrown){ 
     console.log('error(s):'+textStatus, errorThrown); 
    } 
    }); 
}); 
+0

您正在向HTML頁面發送AJAX請求。不能有PHP腳本!但是有一種方法只從返回的頁面獲取div,這是_like_:$(「div」)。load(「index.html #divYouWantToGet」); – 11684

回答

3

給予烏爾格一個id ...將onsubmit =「返回false」,這樣的形式不重裝,或者那些理智最多上提交

HTML

<div id="divID"> <!-- THE DATA FROM THE FORM VIA PHP --> </div> 
<form id='foo' onsubmit="return false"> 
<input type='text' name="yourname"> 
<input type='submit'> 
</form> 

顯示HTML中的響應於ü給一個id。

JQUERY

$('#foo').submit(function(event){ 
    $.ajax({ 
    url: 'index.php', 
    type: 'post', 
    dataType:'html', //expect return data as html from server 
    data: $('#foo').serialize(), 
    success: function(response, textStatus, jqXHR){ 
     $('#divID').html(response); //select the id and put the response in the html 
    }, 
    error: function(jqXHR, textStatus, errorThrown){ 
     console.log('error(s):'+textStatus, errorThrown); 
    } 
}); 
}); 

寫烏爾HTML這裏...我只是打印後可變這裏...ü可以使用<table>(HTML)本所要求

的index.php

echo $_POST['yourname']. 
1

成功:

function(response, textStatus, jqXHR){ 
     do stuff here 
    }, 

如:$("#mydiv").html(response);

0

停止頁面重新加載你會想阻止默認

$('#foo').submit(function(event){ 
event.preventDefault(); 
    $.ajax({ 
    url: 'index.html', 
type: 'post, 
data: $('#foo').serialize(), 
success: function(response, textStatus, jqXHR){ 
    console.log('worked fine'); 
// have the div update here $('div').html(); 
}, 
error: function(jqXHR, textStatus, errorThrown){ 
    console.log('error(s):'+textStatus, errorThrown); 
} 
    }); 
}); 
0

我想你是問如何動態修改網頁內容。 下面是一些示例代碼:

<html> 
<head> 
<script src="./jquery-1.8.2.js"> 
</script> 
<script> 
function test() 
{ 
    var test_div = $("#test_div"); 
    test_div.html("hihihi"); 
} 
</script> 
</head> 
<body> 
<input type="button" onclick="javascript:test();" value="test"/> 
<div id="test_div"> 
test_div here 
</div> 
</body> 
</html> 

您將需要一個服務器端腳本返回的div內容JSON或XML,然後動態修改與返回的JSON/XML的DIV內容。