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

标签 javascript php jquery

我有这个 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 result 的 div 中。

最佳答案

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

$('#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>

关于javascript - 如何通过javascript将输入字段的值发送到php文件并获取返回的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27765210/

相关文章:

php - 在 AJAX 中执行带有变量参数的 php 脚本?

php - 通过将时间戳转换为 unix 时间从 mysql 获取数据

javascript - 从 jQuery 中作为属性的函数访问数据属性

javascript - 从 jsp 调用 React JS

javascript - 从订阅内的其他 VM 在 Azure 虚拟机上定期运行 power-shell 脚本的最佳方法

php - 从特定键迭代 PHP 数组

javascript - 如何使用 jquery 将鼠标悬停在另一个 div 上来滑动 div?

javascript - 页面加载时触发 jQuery 事件

c# - 使用 ASP.NET 和 C# 按页显示记录

jQuery 的 focus() 在模糊() 上再次被触发