Lấy database với ajax
$(document).delegate("#json", "pageinit", function() { $(".manda").click(function(e) { $.ajax({ url : "json1.php", dataType : "json", data : '{"opc":"sim"}', success : function(data){ var html = ""; for($i=0; $i < data.length; $i++){ html += "<strong>Nome:</strong> "+data[$i].nome +" "+ data[$i].sobreNome; html += " <strong>Cidade:</strong> "+data[$i].cidade html += "<br />"; } $("#mostra").html(html); } }); return false; }); });
<?php if ($_POST['opc'] == "sim"){ $var = Array( array( "nome"=>"João", "sobreNome"=>"Silva", "cidade"=>"Maringá" ), array( "nome"=>"Ana", "sobreNome"=>"Rocha", "cidade"=>"Londrina" ), array( "nome"=>"Véra", "sobreNome"=>"Valério", "cidade"=>"Cianorte" )); echo json_encode($var); } ?>
Upload file với ajax
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form id="form" method="post" action="post.php" enctype="multipart/form-data">
<input type="file" name="img"/>
<input type="submit" value="Upload" />
</form>
<script src="jquery.js"></script>
<script src="upload.js"></script>
</body>
</html>
<?php
if($_FILES['img']['error'] > 0) die('Error ' . $_FILES['file']['error']);
if(empty($_FILES['img']['name'])) die('No file sent.');
$tmp = $_FILES['img']['tmp_name'];
if(is_uploaded_file($tmp))
{
if(!move_uploaded_file($tmp, 'img.png')) echo 'error !';
}
else echo 'Upload failed !';
?>
$(function() {
$('#form').submit(function(e) {
e.preventDefault();
data = new FormData($('#form')[0]);
console.log('Submitting');
$.ajax({
type: 'POST',
url: 'post.php',
data: data,
cache: false,
contentType: false,
processData: false
}).done(function(data) {
console.log(data);
}).fail(function(jqXHR,status, errorThrown) {
console.log(errorThrown);
console.log(jqXHR.responseText);
console.log(jqXHR.status);
});
});
});
Không có nhận xét nào:
Đăng nhận xét