我使用以下一组测试文件发送,并在JS和PHP之间获取Ajax请求/响应。以下是文件:
HTML:
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>
JavaScript的:
$(document).ready(function() {
/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "test.php",
type: "post",
data: values,
success: function(data){
alert(data.returned_val);
},
error:function(){
alert("failure");
$("#result").html('There is error while submit');
}
});
});
});
PHP:
<?php
$id = $_POST['bar'];
echo json_encode(array('returned_val' => 'yoho'));
?>
测试步骤:
结果:警告框说:&#34; undefined&#34;。
我错过了什么?