[英]In Ajax How to pass country name in html page to php page?
如何使用ajax将html页面中的国家/地区名称传递到php页面。
demo.php
<html>
<head>
<title>Dynamic Form</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js" ></script>
<script>
$(document).ready(function(){
$("form").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "GET",
url: "post.php",
data: data
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td>
<select name="one" onchange="if (this.value=='other'){this.form['other'].style.visibility='visible';this.form['submit'].style.visibility='visible'}else {this.form['other'].style.visibility='hidden';this.form['submit'].style.visibility='hidden'};"
<option value="" selected="selected">Select...</option>
<option value="India">India</option>
<option value="Pakistan">Pakistan</option>
<option value="Us">Us</option>
<option value="other">Other</option>
</select>
<input type="textbox" name="other" id="other" style="visibility:hidden;"/>
<input type="submit" name="submit" value="Add Country" style="visibility:hidden;"/>
</td>
</tr>
</table>
</form>
</body>
post.php中
<?php
if(isset($_POST['submit']))
{
$Country = $_POST['other'];
echo $Country;
}
?>
当用户从下拉列表中选择其他时,显示一个文本框和一个提交按钮。当用户单击提交按钮时,使用ajax将demo.php的国家名称传递到post.php。
您有一些错误。 $_POST['submit']
永远不会与data = $(this).serialize();
。 因此,您需要检查其他内容。 另外,您在AJAX中将GET
定义为方法,但在PHP中检查$_POST
。 因此,请更改两者之一。 就像是:
HTML / JavaScript:
<html>
<head>
<title>Dynamic Form</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js" ></script>
<script>
$(document).ready(function(){
$("form").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "post.php",
data: data
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td>
<select name="one" onchange="if (this.value=='other'){this.form['other'].style.visibility='visible';this.form['submit'].style.visibility='visible'}else {this.form['other'].style.visibility='hidden';this.form['submit'].style.visibility='hidden'};">
<option value="" selected="selected">Select...</option>
<option value="India">India</option>
<option value="Pakistan">Pakistan</option>
<option value="Us">Us</option>
<option value="other">Other</option>
</select>
<input type="textbox" name="other" id="other" style="visibility:hidden;"/>
<input type="submit" name="submit" value="Add Country" style="visibility:hidden;"/>
</td>
</tr>
</table>
</form>
</body>
PHP:
<?php
if(isset($_POST['other'])) {
$Country = $_POST['other'];
echo $Country;
}
?>
你可以试试这个
$(document).ready(function(){
$("form").on('submit',function(event){
var country = $("select[name=one]").val();
$.ajax({
type: 'POST',
dataType: 'json',
url: "post.php",
data: { country:country},
success: function(json) {
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.