2


我有一个简单的FORM,一个INPUT和一个SUBMIT Button。来自那里的数据将被发送到PHP脚本,该脚本将其发送到 db,然后将其放入DIV中。(与 smarty)
没有 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);
    }
  });
});
4

4 回答 4

4

给你的 div 一个 id...添加 onsubmit="return 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>

在您提供 id 的 html 中显示响应。

查询

$('#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 ......我只是在这里打印 post 变量......你可以<table>根据需要使用 (html)

索引.php

echo $_POST['yourname'].
于 2012-10-18T09:16:53.393 回答
1

成功:

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

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

于 2012-10-18T09:08:17.007 回答
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);
}
  });
});
于 2012-10-18T09:15:57.750 回答
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>

您将需要一个服务器端脚本以 json 或 xml 形式返回 div 内容,然后使用返回的 json/xml 动态修改 div 内容。

于 2012-10-18T09:41:21.417 回答