2015-01-04 21 views
1

我有這樣的HTML代碼:如何通過JavaScript發送輸入字段的值到PHP文件,並得到返回的值

<!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文件中獲取$結果,並在帶有id結果的div中顯示它。

+0

你需要一個提交按鈕,這就是它 – tom10271 2015-01-04 12:09:24

+0

我的意思是,立即得到結果,而不必提交@aokaddaoc – Ikari 2015-01-04 12:16:12

+0

讓一個按鈕,當它點擊,發送一個Ajax請求到該PHP。 – tom10271 2015-01-04 12:17:50

回答

-1

從您的評論中發現,您需要知道如何做AJAX。使用jQuery和一些提示JS部分:

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

相關問題