2014-02-22 53 views
0
<?php 
$num1 = $_REQUEST['num1'] ; 
$num2 = $_REQUEST['num2'] ; 
$tot = $num1 + $num2 ; 
echo "Total is ".$tot ; 
?> 
<html> 
<body> 
<form method="post" action="test.php" > 
<label>#1</label> 
<input type="text" name="num1" /> 
<label>#2</label> 
<input type="text" name="num2" /> 
<input type="submit" value="Add" /> 
</form> 
</html> 

我有這個php。我試圖做的是,只要我進入提交按鈕,結果應該是一個JSON響應。或者通過網址進行回覆。我是json響應的新手。如何創建一個簡單的json響應

這可能嗎?請幫忙。

+0

http://zendguru.wordpress.com/2009/05/04/php-creating-json-response-a-real-world-example/ –

+0

http://www.happycode.info/php-json-response/ –

+0

http://stackoverflow.com/q/9463004/2439156 –

回答

0
$num1 = $_REQUEST['num1'] ; 
$num2 = $_REQUEST['num2'] ; 

$tot = $num1 + $num2 ; 

$response["Total"] = $tot; 
return json_encode($response); 
0

嘗試類似這樣的東西。

$response['status'] = '1'; 
$response['message'] = 'success, you have Json encoded something'; 

header('Content-Type: application/json'); 
echo json_encode($response); 
0

下面是一個簡單的例子,用JavaScript來表示完整性。這也應該跨域,因爲我在響應中加入了jsoncallback。

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
<script> 
$(document).ready(function() { 
$("form").on("submit", function(event) { 
      self = $(this); 
      event.preventDefault(); 
      $.getJSON("/test.php", $(this).serializeArray(), function(response) { 
        console.log(response); 
        self.append("<h3>" + response.total + "</h3>"); 
        }); 
      }); 
}); 
</script> 
<html> 
<body> 
<form> 
<label>#1</label> 
<input type="text" name="num1" /> 
<label>#2</label> 
<input type="text" name="num2" /> 
<input type="submit" value="Add" /> 
</form> 
</html> 

test.php的:

<?php 
header('Content-type: application/json'); 
$num1 = $_REQUEST['num1']; 
$num2 = $_REQUEST['num2']; 
$response["total"] = $num1 + $num2; 
echo $_REQUEST['jsoncallback'] . json_encode($response); 
?> 
相關問題