JQuery ajax 使用

  • JS 端

function xxx_Write() 
{ 	
    var ajaxPostData = {"status": "ok"};

    send_ajax_data(ajaxPostData,
        function(data){
            console.info("AJAX recv " + data["status"] + ".");
        }
    );	
} 

function send_ajax_data(json_data, success_function)
{

    if (success_function == null) {
        console.info("Please pass send_ajax_data function as argument.");
        return ;
    }

    $.ajax({
        url: "xxx_Write.php",
        type: 'POST',
        contentType:'application/json; charset=utf-8',
        data: JSON.stringify(json_data),
        dataType:'json',
        success: function(data){
            //On ajax success do this
            console.info("ajax back infomations success.");
            console.info(data);

            if (data["status"] == "ok"){
                success_function(data);
            } else {
                alert("Please Go To Console Get More Infomations.");

                console.info(data);
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            //On error do this
            //On error do this
            alert("Please Go To Console Get More Infomations.");

            console.info(xhr);
            console.info(ajaxOptions);
            console.info(thrownError);
        }
    });
}
  • PHP 端 xxx_Write.php

<?php header("Access-Control-Allow-Origin: *") ?>
<?php

    $data = json_decode(file_get_contents('php://input'), true);

    echo json_encode($data);
?>
原文地址:https://www.cnblogs.com/chenfulin5/p/13565583.html