But*_*ode 25 javascript form-submit
我有一个用JavaScript构建的函数,我希望在表单提交被执行后执行.它基本上完全改变了页面的外观.但我需要搜索框中的变量才能继续使用JavaScript.此刻它会闪烁并重置那里的内容,因为它会重新加载页面.
所以我在我的函数中设置了一个返回false,这使得它不会这样做,但我想要的变量不会通过表单提交.关于我应该怎么做才能得到它的任何想法?只要该updateTable()功能有效,页面就可以刷新,并且页面重置不会重置.
<form action="" method="get" onsubmit="return updateTable();">
<input name="search" type="text">
<input type="submit" value="Search" >
</form>
Run Code Online (Sandbox Code Playgroud)
这是updateTable功能:
function updateTable() {
var photoViewer = document.getElementById('photoViewer');
var photo = document.getElementById('photo1').href;
var numOfPics = 5;
var columns = 3;
var rows = Math.ceil(numOfPics/columns);
var content="";
var count=0;
content = "<table class='photoViewer' id='photoViewer'>";
for (r = 0; r < rows; r++) {
content +="<tr>";
for (c = 0; c < columns; c++) {
count++;
if(count == numOfPics) break; // check if number of cells is equal number of pictures to stop
content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
}
content +="</tr>";
}
content += "</table>";
photoViewer.innerHTML = content;
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*ant 33
你不能使用正常方式使用表单.相反,你想使用AJAX.
一个示例函数,用于提交数据并提醒页面响应.
function submitForm() {
var http = new XMLHttpRequest();
http.open("POST", "<<whereverTheFormIsGoing>>", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
Run Code Online (Sandbox Code Playgroud)
Ahs*_*hah 29
您可以使用jQuery序列化函数以及get/post,如下所示:
$.get('server.php?' + $('#theForm').serialize())
$.post('server.php', $('#theform').serialize())
Run Code Online (Sandbox Code Playgroud)
jQuery Serialize Documentation:http://api.jquery.com/serialize/
使用jQuery提交简单的AJAX:
// this is the id of the submit button
$("#submitButtonId").click(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
152299 次 |
| 最近记录: |