<html>
<head>
<meta charset="utf-8" />
<title>jQuery Ajax - POST</title>
<script type="text/javascript" src="jquery_1.6.1.js"></script>
<script type="text/javascript"><!--
$(document).ready(function() {
$('form').submit(function() {
var data = 'name='+$('#nm').val();
var data = 'name='+$('#sn').val();
$.post('script.php', data, function(response){
$('#dv').html(response);
$('#dv2').html(response);
});
return false; // required to not open the page when form is submited
});
});
--></script>
</head>
<body>
<div id="dv">Here will be displayed the response.</div><br />
<form action="script.php" method="post">
Name: <input type="text" name="nm" id="nm" /><br />
<div id="dv2">Here will be displayed the 2nd response.</div><br />
Second name: <input type="text" name="sn" id="sn" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
我希望Name发布到JavaScript并在divtag(dv)和第二个名称下面出来(dv2) - 我环顾四周,我似乎找到的只是如何在一个div标签中回显变量。
答案 0 :(得分:0)
检查一下。您为传递给script.php的数据声明了相同的名称。这是编辑过的代码。它正在运行。
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Ajax - POST</title>
<script type="text/javascript" src="jquery_1.6.1.js"></script>
<script type="text/javascript"><!--
$(document).ready(function() {
$('form').submit(function() {
var nm = $('#nm').val(); // changes made
var sn= $('#sn').val();
$.post('script.php',{
name1:nm,
name2:sn
}, function(response){
var resp=response.split("."); // spiltting into different output
$('#dv').html(resp[0]);
$('#dv2').html(resp[1]);
});
return false; // required to not open the page when form is submited
});
});
--></script>
</head>
<body>
<div id="dv">Here will be displayed the response.</div><br />
<form method="post"> // no need to specify script.php here
Name: <input type="text" name="nm" id="nm" /><br />
<div id="dv2">Here will be displayed the 2nd response.</div><br />
Second name: <input type="text" name="sn" id="sn" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
获取script.php中的参数,如下所示
<?php
String name1 =$_POST["name1"];
String name2= $_POST["name2"];
// do your calculations
String together= name1 +"."+ name2; // just make different output together as one string
out.print(together);
?>