Jex’s Note

Ajax (GET, POST, JSON)

jQuery

$(document).ready(function(){
    $.ajax({
        url: '/test/test_response.php',
        type: "POST",
        data: 'test=1&test2=33',
        beforeSend: function(html) {
            $('#loading').removeClass('hide');
        },
        success: function(response) {
            alert(response);
        },
        complete: function () {
           $('#loading').addClass('hide');
        },
        error: function(xhr, statusText, err){
          alert("Error:" + xhr.status);
        }
    });
});

PHP

POST :

header('Content-Type: application/json');
echo 'test='.$_POST['test'].'; test2= '.$_POST['test2'];

GET :

echo 'test='.$_GET['test'].'; test2= '.$_GET['test2'];

JSON :

$value = json_decode(file_get_contents('php://input'));         //取得JSON字串並且解析
echo json_encode($value);                                       //將$value轉成JSON格式傳回

Comments