有时我们不希望用户点击提交来请求服务器数据, 利用Jquery可以实现。
test.html
<!DOCTYPE html>
<html>
<body>
<div id="select">
<input name="show" type="radio" value="all" /> <label for="all"> All</label>
<input name="show" type="radio" value="rank" /> <label for="rank"> Top10</label>
</div>
<div>
<form action="data.html" method="post">
<textarea id="res" name="res" row="4"></textarea><br />
<input type="submit" value="Submit" />
</form>
</div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="submit.js"></script>
</body>
</html>
submit.js
$(function () {
//alert('works!');
var url = 'http://localhost:8080/test/data.php';
var input=$('input[type="radio"]');
var res=$('#res');
input.click(function () {
$(this).attr('checked');
var type = $(this).val();
console.log(type);
$.ajax({
url: url,
data: {'type': type },
dataType: 'json'
})
.success(function( data ){
res.html( data );
console.log( data );
});
});
});
data.php
<?php
if (isset($_GET['type'] )){
echo json_encode([$_GET['type'] , ' Method']);
}else{
echo 'ERROR';
}
?>








网友评论