如何通过javascript将输入字段的值发送到php文件并获取返回的值


How to send a value of a input field through javascript to a php file and get the values returned

我有这个html代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
     <form action="test.php" method="get">
        <input type="text" placeholder="City" id="city" />
        <br />
        <input type="text" placeholder="Region" id="region" />
     </form>
     <div id="result"></div>
</body>
</html>

这是我的php代码:

<?php
     $city = $_GET['city'];
     $region = $_GET['region'];
     $result = "You entered " . $city . " and " . $region;
?>

我想立即从 php 文件中获取$result,并在带有 id 结果的div 中显示它。

从您的评论中可以看出,您需要知道如何执行 AJAX。在jS部分使用jQuery和一些提示:

$('#region').mouseout(function() {
	$('#result').fadeOut();
	$.ajax({
		url: window.location.href+"api/user/"+$(this).val(),
		dataType: "html"
	}).done(function(data) {
		$('#result').fadeIn();
		$('#result').text(data);
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>